mike74 said:
It says "they're equal". Does anyone know why?
Because the numeric standard for the language says so. Positive and negative zeros compare as equal, despite not being bitwise identical.
There are many rules about the encoding of floating point, and the standards specify what happens.
You can read the basis of it for Java 21 here, but this specific behavior has been the same since the beginning of the language. Look down a few paragraphs to read “Positive zero and negative zero compare equal, so the result of the expression 0.0==-0.0
is true
and the result of 0.0>-0.0
is false. Other operations can distinguish positive and negative zero; for example, 1.0/0.0
has the value positive infinity, while the value of 1.0/-0.0
is negative infinity.”
It is that way because the standard says so. They chose it because other standards also say so. This works back until you get to the level of either mathematicians or electrical engineers declaring that method works better in their numeric system.
mike74 said:
I thought positive zero and negative zero were two different numbers in “double”.
They are. They have different binary encodings. That doesn't mean they're not equivalent.
There are often many ways to represent things that are functionally equivalent. Perhaps as a parallel, 1000 is the same value as 10^3, while the representations are different the number they represent is the same.
There are many things in the language and the libraries where equality does not mean bitwise equivalence.
mike74 said:
Does it do two checks if you do a zero comparison with a double?
It might. That detail is abstracted away by your language.
You don't know what the underlying system is. You might be on a processor that doesn't have a floating point processor. You might have a processer that only has 32-bit floating point support and needs to do extra work for 64-bit double precision. You might be on a system that has 80-bit precision which needs to do extra work to clamp it down to 64-bit precision.
The work for the comparison might be a single CPU instruction. It might be a series of mixed CPU and FPU instructions. It might be a set of work to send work to a separate math co-processor on a separate chip and stall for the result. It might be several hundred instructions to run the operation without using any floating point hardware.
The entire point of the language abstraction is that you don't need to know or care what is going on under the hood.