Is it possible to check the double "d <0"?

I am writing a complete dual float function for Arduino (it does not matter, but I could not find any "correct" ones), and I am doing this check:

 if (d < 0) { d *= -1; bin += "-"; } 

I know because of floating point inaccuracies, double equality is fictitious. Is it safe to do this? Or should I stick with this (which I use in subsequent parts of my code anyway)

 int compareNums(double x, double y) { if (abs(x - y) <= EPSILON) { return 0; } else if (x > y) { return 1; } else { return -1; } } 

And a few simple questions: does it matter if I do d < 0 or d < 0.0 ?

I multiply double d by 10 until it has a fractional part, so I do a check similar to d == (int) d . I am wondering what good epsilon to use (I used it here http://msdn.microsoft.com/en-us/library/6x7575x3(v=vs.80).aspx ), since I do not want an infinite loop. According to article 0.000000119209 , this is the smallest distinguishable difference for floats or something like that.

thanks

+4
source share
2 answers

d < 0 valid (although I would prefer to write d < 0.0 . In the first case, zero will "advance" until doubling before comparison.

And comparing double to zero with < or > completely fair and does not require "epsilon".

bin += "-"; is pointless.

In general, comparing float / doubles with "==" is invalid and should never be done (except in some special cases, such as checking for zero or infinity). Some languages ​​do not even allow "==" (or equivalent) between floats.

d == (int) d more stupid.

+2
source

See my answer to this question:

How dangerous is comparing floating point values?

In particular, recommendations that you should not use absolute epsilons, and should not use floating points, until you fully read and understand what every computer scientist needs to know about floating point arithmetic.

As for this specific piece of code in your question, where it seems your goal is to print a textual representation of the number, just testing < 0 will be correct. And it doesn't matter if you write 0 or 0.0 .

+1
source

All Articles