-
Notifications
You must be signed in to change notification settings - Fork 26
Float comparisons #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Comparing |
Are these actually used anywhere in the library itself? |
Yes, |
Know why those are using floats? |
Ah I think I misunderstood your original questions. The library itself never creates a " |
cmpfn.{c,h}
define comparison functions for many types, includingfloat
s anddouble
s. It defines them like so:IEEE floating point numbers should not be compared for equality. (Source). As it currently stands, structures that uses a
CompareFn
(BST
andHashMap
for example) are inherently implementation defined. This does not seem suitable for a library with "portable" in its name.A simple fix would be to change
v1==v2
to something likeabs(v1 - v2) < DBL_EPSILON
, however, this creates a scenario in which one double is, conceptually, both equal to and less/greater than another -- in other words, a partial ordering.The description and implementation of these functions imply that a
CompareFn
will produce a total ordering; this is fundamentally incompatible with IEEE floating point numbers, as they are only partially orderable. Consequently, any structures which assume a total ordering (e.g.BST
) could still exhibit strange behavior with the epsilon solution.I would propose two ways of dealing with this. One would be to remove
doubleCmpFn
andfloatCmpFn
, and have types that useCompareFn
s throw an error if they are given floating point numbers. The other would be somewhat more complicated as it would involve creating an additionalPartialCompareFn
interface and implementing it for types which are partially orderable (a superset of types that are totally orderable). Incidentally this is how ordering is done in the Rust standard library, which exports twotrait
s (somewhat analogous to Java interfaces): Ord and PartialOrd.The text was updated successfully, but these errors were encountered: