Some floating point values โ€‹โ€‹should sum to zero in PHP, but not

Possible duplicate:
Floating point inaccuracy examples

<?php $a = 128.3; $b = 140.7; $c = 12.4; echo $a-$b+$c; //2.30926389122E-14 ?> 

it will display "2.30926389122E-14"

Why is it not equal to zero?

 <?php $a = 112.7; $b = 125.2; $c = 12.5; echo $a-$b+$c; //0 ?> 

What is the difference between the two?

+3
source share
2 answers

The PHP doc answers this better than I could:

Floating point numbers are limited by precision. Although it depends on the system, PHP usually uses IEEE 754 with double precision, giving the maximum relative error due to rounding of the order of 1.11e-16. Non-elementary arithmetic operations can lead to large errors and Of course, error propagation should be if several operations are exacerbated.

In addition, rational numbers that exactly represent the floating point number in base 10, such as 0.1 or 0.7, do not have an exact representation as a floating point number in base 2, which is used internally, regardless of the size of the mantissa. Consequently, they cannot be converted to their internal binary counterparties without a slight loss of accuracy. This can lead to confusing results: for example, gender ((0,1 + 0,7) * 10) usually return 7 instead of the expected 8, since the internal representation will be something like +7.9999999999999991118 ....

So never trust floating-point results to the last digit and never compare floating point numbers for equality. If higher accuracy is required, arbitrary mathematical precision functions and gmp functions are available.

Edit: The name of the question is asked how to fix it. It's just ... rounding. $val = round($val, 2);

+4
source

This is not a mistake; it is a very well-documented phenomenon of the IEEE754 floating point standards.

There is a limited number of bits to represent floating point numbers, and there is, let me see if I can remember, yes, an infinite number of real numbers between any two different numbers.

This means that you cannot represent all real numbers, but must provide approximations.

A way to fix this does not mean that numbers can be represented accurately. You must determine if the number is enough to be zero and not equal to zero, and you can do this by choosing a suitable small error value based on your numbers and operations.

Read What Every Computer Scientist Should Know About Floating-Point Arithmetic as a Detailed Treatise (Warning, this can be a bit difficult to read), or the Floating-Point Guide has a softer introduction, as well as a link to > PHP Math Package (arbitrary precision arithmetic), which may be useful to you.

+11
source

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


All Articles