why does Float static compare not require an epsilon value?
Upon checking Float.compare(f1,f2) I found that it compares f1f2
and returns -1,0,1.Then it returns -1,0,1 if the values are -0.0, 0.0 or NAN.
What does that mean -0.0?I would have expected something like
开发者_StackOverflow中文版 return (Math.abs(f1 - f2) - 0.001f) > 0)
where 0.001 is a given epsilon value.
Thanks.-0.0
is the negative zero, as specified by the IEEE 754 standard.
If you're curious about how such a value might arise, the following article does a good job of explaining it: http://www.savrola.com/resources/negative_zero.html
As to not taking an epsilon value, this is how Float.compare
is designed work (it's an exact comparison, not an approximate one). There's nothing to stop you from having another comparison function that does take an epsilon and does perform an approximate comparison.
Both exact and approximate comparisons of floating-point numbers have their uses.
As to your actual code, it suffers from a number of issues:
- it isn't a three-way comparison like
Float.compare
; - it doesn't handle
NaN
s; - it is generally better to specify the epsilon as a relative value, not as an absolute one, so that it scales with
f1
andf2
(see this article for a discussion).
My point here isn't to criticise your code but to show that writing good floating-point code is harder than it first looks.
Floating point arithmetic is tricky. This article throws some light on the basics.
-0 is signed zero:
In ordinary arithmetic, −0 = +0 = 0. However, in computing, some number representations allow for the existence of two zeros, often denoted by −0 (negative zero) and +0 (positive zero).
[...]
The IEEE 754 standard for floating point arithmetic (presently used by most computers and programming languages that support floating point numbers) requires both +0 and −0. The zeroes can be considered as a variant of the extended real number line such that 1/−0 = −∞ and 1/+0 = +∞, division by zero is only undefined for ±0/±0 and ±∞/±∞.
精彩评论