Why is PHP float 0 (zero) displayed with a sign?

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

 $x = 0; echo $x; 

0 displayed. If you multiply this 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 get the result: -0 .

Why? Shouldn't you always show zero unsigned, regardless of its base type?

+5
source share
2 answers

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

1) sign (1 bit)

2) indicator (11 bits)

3) fraction (52 bit)

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

Integers use two additions, where the most significant bit (MSB) defines the sign. MSB is 0 if you multiply by 0.

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

+1
source

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

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

For example, see W. Kahan's article, "Branch passages for complex elementary functions or a lot of unsigned noise . "

+1
source

Source: https://habr.com/ru/post/1245191/


All Articles