Comparing floating point numbers in an intuitive way fails within julia

The ==/< and isequal/isless orderings serve different purposes. The ==/< operators implement standard and standardized comparison behaviors for use in writing numerical code. This is how NaN and -0.0 behave in C, C++, Fortran, Matlab, Python, Perl, R, Ruby, etc.—so many that I have to wonder what languages you’ve been using that you haven’t encountered this before?

The isequal/isless operators are designed for hashing and sorting. We have isless(-0.0, 0.0) and therefore !isequal(-0.0, 0.0) for two major reasons:

  1. So that the sort order of ±0.0 is deterministic and value-based, with negative zeros sorting before positive zeros;
  2. Because it’s fairly common for numerical functions (with branch cuts, for example) to treat negative and positive zeros differently, so if you’re memoizing a function with a hash, you want 0.0 and -0.0 to hash differently so that you can save different answers for them.

Of course, there are situations where this is inconvenient, annoying or surprising. There was a long discussion of this point in this issue in response to an earlier discourse thread. You may want to read that discussion and this post from the original thread in which I outlined much of the reasoning behind the current behaviors.

Questions and feedback are welcomed, but you may want to keep a few things in mind:

  1. It’s safe to assume that every numerical behavior in Julia has been extensively discussed and debated by experts over the 8 years of development leading to Julia 1.0.
  2. Behaviors in 1.0 and are not eligible to change until Julia 2.0, so while discussion of improvements is encouraged, the timeline for changing them is not immediate.
  3. The rhetorical style of your first post makes it a bit difficult to respond neutrally; a more genuinely inquisitive rather than dramatically outraged approach is likely to come off better.

If you find the built-in == unsuitable, you can define your own == operator and use the standard == syntax. Readers of your code may find this confusing, however, so while it’s possible, it may not be advisable.

Thanks for the inquiry!

12 Likes