Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is (x - x) always positive zero for doubles, or sometimes negative zero?

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)?

like image 842
jtbandes Avatar asked Jul 25 '14 08:07

jtbandes


People also ask

Does positive zero have negative zero?

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.

How do you know if a double is not zero?

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.

Is 0 and negative 0 the same?

“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.

Can there be a negative 0?

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.


1 Answers

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.

like image 180
Pascal Cuoq Avatar answered Sep 22 '22 17:09

Pascal Cuoq