Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP's float 0 (zero) is being displayed with sign?

In PHP, lets create a variable and set it value to 0:

$x = 0;
echo $x;

it would display 0. If one would multiply that by -1:

$x = -1 * $x;
echo $x;

we still see 0. But if $x is a float:

$x = 0;
$x = (float)$x;
$x = -1 * $x;
echo $x;

we would get the output: -0.

Why is that? Shouldn't zero be always displayed unsigned, regardless of its underlying type?

like image 444
Gacek Avatar asked Oct 31 '22 07:10

Gacek


2 Answers

Because PHP typically uses the IEEE 754 double precision format for floating point numbers which consists of:

1) sign (1 bit)

2) exponent (11 bit)

3) fraction (52 bit)

If you multiply $x with -1 the sign bit is set.

Integers use the two complement where the most significant bit (MSB) determines the sign. The MSB is 0 if you multiply with 0.

See: https://en.wikipedia.org/wiki/Signed_zero

like image 143
Rocki Avatar answered Nov 10 '22 20:11

Rocki


Floating point zero is used for more than just absolute zero. It is used to represent tiny results, too small absolute magnitude even for subnormal numbers.

In some calculations, the sign of such numbers does matter. For example, it matters that 1/+0 is positive infinity, but 1/-0 is negative infinity. To make that work right, multiplying 0 by -1 gives -0.

For example, See W. Kahan's paper "Branch Cuts for Complex Elementary Functions or Much Ado About Nothing's Sign Bit".

like image 34
Patricia Shanahan Avatar answered Nov 10 '22 19:11

Patricia Shanahan