Reputation: 5131
I'm writing a full double to float function for the Arduino (irrelevant, but I couldn't find any "proper" ones) and I do this check:
if (d < 0) {
d *= -1;
bin += "-";
}
I know because of floating point imprecisions double equality is finicky. So is it safe to do that? Or should I stick to this (which I use in later parts of my code anyways)
int compareNums(double x, double y) {
if (abs(x - y) <= EPSILON) {
return 0;
} else if (x > y) {
return 1;
} else {
return -1;
}
}
And a couple quick questions: does it matter if I do d < 0
or d < 0.0
?
I'm multiplying a double d
by 10 until it has no fractional part, so I do a check similar to d == (int) d
. I'm wondering what's a good epsilon to use (I used this here http://msdn.microsoft.com/en-us/library/6x7575x3(v=vs.80).aspx), since I don't want to end up with an infinite loop. According to the article 0.000000119209
is the smallest distinguishable difference for floats or something like that.
Thanks
Upvotes: 4
Views: 302
Reputation: 47749
d < 0
is valid (though I'd prefer to write d < 0.0
. In the first case the zero will be "promoted" to double before the comparison.
And comparing double to zero with <
or >
is perfectly valid, and does not require an "epsilon".
bin += "-";
is nonsensical.
In general comparing floats/doubles with "==" is invalid and should never be done (except for some special cases such as checking for zero or infinity). Some languages do not even allow "==" (or equivalent) between floats.
d == (int) d
is more nonsense.
Upvotes: 2
Reputation: 215547
See my answer to this question:
How dangerous is it to compare floating point values?
Specifically, the recommendations that you should not be using absolute epsilons and should not be using floating point whatsoever until you've thoroughly read and understood What Every Computer Scientist Should 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, simply testing < 0
is correct. And it does not matter whether you write 0
or 0.0
.
Upvotes: 1