161 points · by todsacerdoti · 3y ago · 229 comments
That's not at all true. The inclusion of negative zero in ieee 754 was a deliberate design choice, and if it were considered desirable that zero should be unsigned, then the bit pattern assigned to -0 would not have been so assigned. See 'much ado about nothing's sign bit'[0], by one of the principal authors of ieee 754.
Whereas -0 and +0 are not operationally equivalent, operational equivalence is an important and useful relation; see the very pattern matching example linked from the OP[1].
This is actually a valid distinction because these values can represent different values.
Floating point values are not numbers, but ranges of possible values: float -0 is a number in the range (-FLT_TRUE_MIN / 2, 0] and float +0 is a number in the range [0, FLT_TRUE_MIN).
IMO if I were to redesign IEEE 754 I would add a third float 0 value that always represents exactly 0 and redefine float -0 and float +0 as open limits, but that would probably make everything a lot more complicated.
1/0 is infinity but 1/(-0) is -infinity
what we have is lim(x->0+) 1/x = +inf and lim(x->0-) 1/x = -inf
=:= (=== in elixir) Somewhat means "and has the same binary form"
Fwiw, julia made the exact same choices.
+0.0 == -0.0 is true, I guess because they are very close
+0.0 =:= -0.0 is false, I guess because they have different bits
A =:= B for two different numbers of course, because they have different bits
How does == work for other very close floating point values in Erlang? Is there some inconsistency here?
While =:= is not something mandated by IEEE. Erlang implements such an operator on floats and it decides to compare false for 0.0 & -0.0. So it probably compares bits/does integer comparisons on same data
-0.0 is a weird dumb non mathematical value that IEEE 754 put in (for example the standardized value for sqrt(-0.0) is not even justifiable based on their choices). I think they didn't want 1/(1/-Inf) to be Inf, or something.
In the end think of erlang's "==" as "equal in value" and "=:=" as "equal in representation in memory".
Now if you really want to raise the hackles of someone using Erlang, should ask why integers and floats don't have a well ordering, and what you should do when you sort them.
HN is full of people who think the world needs their hot take based on a headline, unfortunately.
What for though?
I was expecting as I learned Rust that I would soon find the == operator (which is just the predicate PartialEq::eq) wasn't quite enough and need some === type operator (Rust doesn't have one), but I never did. Turns out actually in most cases equality is what I cared about.
Zero is already special cased in IEEE 754 (along with the rest of the denormals, because of the implied leading mantissa bit), the implementation would be no harder if you just only had a single zero. However, back when the standard was being created, when a single zero value was proposed there was pushback from people in the user community who depended on knowing which side of the zero they underflowed on their own floating point implementations.
Many people think that negative zero is just an engineering artefact. This is not true, it is a feature that was asked for, debated, and then added...
... almost certainly because it was an engineering artefact in a previous system that someone managed to depend on, https://xkcd.com/1172/ style.
In the case of +0.0 and -0.0, they can be treated as values between zero and the smallest representable number (about 5.4E-079 for 32 bit floats). It isn't a very common use case since dealing with such small numbers isn't a very common thing, but it is definitely a possibility.
And maybe complex number shenanigans and multi valued functions? Maybe someone familiar with mathematics can tell us more. :)
if you want to say "zero approaching from negative one", fine, say that. but that IS NOT the same thing as -0. zero is just zero, it doesn't have a sign.
some people just want everything to fit in a nice neat box, and sometimes folks, life is not like that. this is an awful change, injecting meaning where there is no room for it.
Compare/contrast: the JSON document "0" vs the JSON document "0.0". Both encode the same type (JSON only has one Number type) and so the same mathematical object — which is, again, 0 — but these are distinct JSON documents.
And that's the whole point of this change. Erlang == is mathematical equality. Erlang =:= is (encoded bit-pattern) representational equality.
Which is often the kind of equality you care about, if you have canonicalization happening at parse time, and so you want to implicitly assert (usually for added efficiency!) that the values you got after parsing + mathing are not only mathematically equal to some value, but representationally equal to that value.
---
(If this irks you as a mathematician, you could model IEEE754 as its own mathematical group — a lattice, I think? — of which +0 and -0 would be members. Along with with some — but not all — base-2 rationals; and a random assortment of signalling and non-signalling NaNs.)
nope. both those documents are a STRING type, not a number type.
I'm wondering what they are going to do with other operators, >=, <= etc
However, there are cases where comparing floating point numbers for equality works just fine. For example, if you have a variable 'v' and want to update it to a new value 'f', you can do 'if (v == f)' to check if the variable would change. Or if you have a sentinel value -1.0, it is perfectly ok to do 'if (a == -1.0)'
In general, if you look for a number 'f' in variable 'v', you can safely use equality as along as you expect 'v' to be set to 'f', i.e. the value of 'v' is not the result of a computation. This may sound trivial, but this is often omitted when discussing floating point comparison. If someone knows a scenario where the examples above would break, I would be curious to hear! (My main field is audio programming and code like this is omnipresent.)
almost invariably floating-point calculations end up in some kind of comparison; if they didn't we'd probably do the calculations in a galois field or something instead
even equality comparison of floats is useful; there are an abundance of seminumerical algorithms which use it correctly on the results of computations. a trivial example is computing an attractive fixpoint by iterating a function and comparing each hare result to the previous iteration and to a tortoise. you have to be especially careful about x87 extended precision here
ieee-754 requires bit-exact results for the five fundamental operations
here is an example where your 'safe' generalization is not safe:
#include <stdio.h>
int main()
{
float f = 0.7;
printf(f == 0.7 ? "ok\n" : "wtf\n");
return 0;
}
this prints 'wtf' on, for example, x86_64-linux-gnuI'm pretty sure OP meant comparison for equality, not comparison in general (which would be absurd, indeed).
> even equality comparison of floats is useful
That's exactly what I tried to point out. However, these are really special cases and you need to be careful and know what you are doing.
I am a quickly crustifying developer who was an enthusiatic value packer in their younger years but I've changed my tune to be less afraid of using more variables if they are clearer - even if that comes at a cost to data efficiency (and like, an extremely negligible cost in most situations). Though I don't have any objections to value packing for serialization - that's a fundamentally different domain.
Isn't it strictly faster to simply assign? No branching, no branch predictions, only one instruction in all cases.
float freq = getParameter(FILTER_FREQUENCY);
float coeff;
if (freq != mFreq) {
coeff = calculateCoeffFromFrequency(freq); // expensive
mFreq = freq;
mCoeff = coeff;
} else {
coeff = mCoeff; // use cached value
}
// use coeffOf course, that observation may be more or less useful, depending on circumstances.
-4 always removes 4, whether or not there is a number to the left.
The only acceptable grammar for math is s-expressions.
I think that this is an oversimplification, and misses a key point.
Floating point numbers can be interpreted in (at least) two distinct ways.
In one use model, floating point numbers allow a sparse representation of selected points on the (extended) real number line. In this model, the numbers themselves are perfectly precise, and the basic operations do exactly what you'd expect -- but because the result of the expected real-number operation may not be one of the selected representable points, each operation is potentially paired with a second, implicit, rounding operation, and the consequences of the cumulative effects of this rounding operation take some thought.
This first model is often comfortable for those who have done low-level numerical program with sized integers, which are likewise a selected sparse representation of selected points on the integer line. While rounding comes up in fewer operations here, and is simpler, wrap-around becomes an issue.
However, a second model of floating point numbers is that each possible bit sequence represents an /interval/ on the (extended) real number line. In versions of this model, while the set of representable intervals is still very restricted, every point on the real number line falls into a representable interval, which is a property that sometimes eases (and sometimes seems to ease) analysis. In exchange, the operations are much more complex, and their limitations are much more obvious -- in particular, not only can no disjoint intervals be represented, but for any given point on the real line only one interval that contains it is representable -- there's no way to represent intervals of different sizes containing (some of) the same points.
This second model is what people are mostly thinking of when they say that floating point arithmetic is "not precise." In particular, both the inputs and outputs of operations have imprecise interpretations -- that is, the input interval contains infinitely many indistinguishable points, and the output interval contains infinitely many indistinguishable points, even if a real number equivalent of the problem would have a single number in the desired range.
When extended to true interval arithmetic, the second model can be very useful for understanding error propagation and uncertainty, but sadly this is rarely done.
as you point out, the second model can be implemented
Without operators, all you have is a set of objects which you can't tell apart.
[1] https://numpy.org/doc/stable/reference/generated/numpy.isclo...
[2] https://docs.python.org/3/library/math.html#math.isclose
[1] https://www.erlang.org/doc/reference_manual/expressions.html...
This is a sad state of affairs, but nobody was fixing this in the last 30 years, so there's that.
As matter of fact, business apps are by far the longest portion of the apps. Just considering all spreadsheets, almost all RDBMS, etc alone.
Binary Floating-point is what is ACTUALLY niche. And it not look like it just because is the default, similar how in certain niches "0" is "true".
Physics simulations too.
but is there a better algebraic structure to use when thinking of floats? like, in terms of limits, or something that tracks significant digits and uncertainty? how do formal methods handle these?
Can you motivate this with an example for me? For instance, I think of games or location data encoded as FP; then, clearly, comparing them is a critical task to know questions like "what is closer" and so on.
What am I missing?
Floating point numbers lose precision because binary arithmetic doesn't represent decimal in all cases ( 1/3 is an easy example). It's not hard to get into a situation where you're asking if a number is 0.0 but due to a precision error the number you have is 0.00000000000001 or whatever and it should have been zero.
If you're dealing with anything where precision is paramount (i.e. money or high precision machining) you should consider using something else that matches the real work precision you are trying to model.
You can, of course, use floats and test differences rather than strict equality (i.e. distance is < 0.01) and that's fine too... if you remember to do it, and account for the potential for small precision differences to propagate throughout your calculations and accumulate into larger errors.
That’s not the reason. A counterexample is decimal arithmetic. That represents decimal in all cases, yet loses precision when doing calculations. Once you start doing division that applies even to arbitrarily sized decimal numbers.
The correct reason is because the subset of the reals that is representable as IEEE float isn’t closed under the operations people want to perform on them, including the basic ones of addition, multiplication and division.
You never use the word “comparison” again in the comment!
Strict inequality (> and <) comparison are generally fine as long as you avoid NaNs.
Well, followup, if some error Epsilon can be introduced during any manipulations, when you check for strict inequalities do you check x < y + Epsilon? Does the language implicitly do it for you?
Playing with Python3:
>>> +0.0==-0.0 True
The C in GCC below also returns 1:
#include <stdio.h>
int main()
{
float a = +0.0;
float b = -0.0;
printf("%d\n", a == b);
}You'll get the same in python with
>>> -0. is 0.
False
Python 3.11 gives me this:
>>> -0 is 0 <stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="? True
Because (a) -0 is an integer, and there is only one integer zero, (b) small numbers have only one instance in memory as an optimization.
I would even be happy with a default set of compiler warnings or errors, which I don’t believe I have ever seen.
There can be a separate function `float_equals()` with explicit args that does what people want
The only reason to use the same syntax == is for POLYMORPHIC code that is actually correct.
But it's not going to be correct with floats, because they don't obey the same algebraic laws ... So the syntax should be different!
---
I believe the Erlang compiler optimization presented as justification for this change is a good example
The compiler wants to reason about code, independent of types
But that reasoning about the =:= operator is wrong for the float case.
they're already familiar with rounding errors
from that perspective you're suggesting taking a step backwards from fortran i toward assembly language
the erlang compiler bug presented is not an example of what you're talking about because you're talking about arithmetic, and the buggy comparison operator it's using is not an arithmetic comparison operator
The solution is to either use decimal floats if they suit your need (and eat the performance penalty), or to use a linter that flags float comparisons by equality.
Another one is that you would lose transitivity on equality. With a 1% epsilon, you would have
1.000 == 1.005
1.005 == 1.010
1.010 == 1.015
but 1.000 != 1.015
You also would have to be careful on how to define that 1% error range. the naive "x is equal to all numbers between 0.99x and 1.01x" would mean 1.0 would be considered equal to 0.99, but 0.99 would not be considered equal to 1.0 (1.01 times 0.99 is less than 1.0)You also lose that, if a == b and c == d it follows that a + c == b + d.
The behavior around zero also will go against intuition. If you consider 0.99 and 1.0 to be equal, do you really want 1.0E-100 and -1.0E-100 be different?
Then it wouldn't really be an equality comparison any more. For instance according to your rule 1.0 and 1.01 are the same number, but they clearly are not. But if you want to do this regularly you could create a special type and overload the equality operator (if your language supports it, otherwise you'll have to call the function directly) that points to 'boolean about_equal(float f1, float f2, float epsilon)' or something equivalent where epsilon is the amount that you would allow f1 and f2 to deviate from each other to still call them equal. And you could define epsilon as ((abs(f1) + abs(f2)) / 100) .
The bitwise comparison isn't 'blatantly wrong', it's the expected behavior in just about every programming language. I'm not aware of any language that has a native float operator that does this but as you can see you can usually simply add one yourself if you really need it. But this need rarely comes up and usually indicates that you are doing something wrong.
> The == operator will continue to return true for 0.0 == -0.0.
For example, the quantity (try it in Python):
0.1 ** 100 / 1000**100 evaluates to 0.0
while the quantity 0.1 ** 100 / (-1000**100) evaluates to -0.0
It's clear that neither the two quantities are 0 (no division can produce a result that is exactly zero!) but they approach the zero. But one quantity is slightly less than zero, the other slightly more than zero.Of course for integers -0 doesn't make sense (that is the reason why we invented 2 complement, to not have 2 "zeros")
no, its not. zero is zero, its nothing. "a quantity approaching to zero" is "a quantity approaching to zero". its easy to remember because zero is not a quantity, its a lack of quantity, by definition.
these are two distinct concepts, which some people mistake as the same item.
Stand in place and turn around: how far did you go from where you started?
Nonetheless, I agree. It's a bad idea.
But yeah, you’re right
1> 1==1.0.
true
2> 1=:=1.0.
false
You can think of it as analogous to == vs === in JS, except that the "type safety" here really only refers to different numeric types (and in JS there is no such distinction)[1]: https://www.erlang.org/doc/reference_manual/expressions.html...
In Geometry for Programmers, I reference a case when an automated test system caught a "zero-not-zero" bug, and I couldn't reproduce it with a unit test until I finally realized that the test system was comparing XMLs not numbers. In print, "-0." and "0." are, of course, different, although in runtime they pretend to be the same.
More interesting to me is how they are introducing this change, both in the previous OTP and next, and how they will arm people with tools to hopefully identify and understand the impact. I wonder how many folks will actually be impacted?
* Sperry Univac 1100/62
The change in the article is about =:=, so NaN =:= NaN does not have to give the same answer as NaN == NaN.
IEEE 754-2008 5.11: "Comparisons shall ignore the sign of zero (so +0 = −0)."
And also because that's what the most common spec demands.
+0.0 = 0
Hence -0.0 = +0.0 right ?