When x
is a double
, is (x - x)
guaranteed to be +0.0
, or might it sometimes be -0.0
(depending on the sign of x
)?
However, in computing, some number representations allow for the existence of two zeros, often denoted by −0 (negative zero) and +0 (positive zero), regarded as equal by the numerical comparison operations but with possible different behaviors in particular operations.
if(value != 0) //divide by value is safe when value is not exactly zero. Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0. +1 for making it clear that only class scope numeric primitives are initialized to zero.
“Signed zero is zero with an associated sign. In ordinary arithmetic, the number 0 does not have a sign, so that −0, +0 and 0 are identical.
There's no such thing as negative zero. For a binary integer, setting the sign bit to 1 and all other bits to zero, you get the smallest negative value for that integer size. (Assuming signed numbers.) Negative zero is actually used in mathematical analysis, especially in limit calculations.
x - x
can be +0.0
or NaN
. There are no other values it can take in IEEE 754 arithmetics in round-to-nearest (and in Java, the rounding mode is always round-to-nearest). The subtraction of two identical finite values is defined as producing +0.0
in this rounding mode. Mark Dickinson, in comments below, cites the IEEE 754 standard as saying, section 6.3:
When the sum of two operands with opposite signs (or the difference of two operands with like signs) is exactly zero, the sign of that sum (or difference) shall be +0 in all rounding-direction attributes except roundTowardNegative [...].
This page shows that in particular 0.0 - 0.0
and -0.0 - (-0.0)
are both +0.0
.
Infinities and NaN both produce NaN when subtracted from themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With