Formulas for comparing float equality in PHP

The question of how to compare floating point numbers was given here . This question is different in what I ask about formulas. The two highest voice responses have a slightly different solution to the problem:

if (abs(($a-$b)/$b) < $epsilon) { … }

and

if (abs($a-$b) < $epsilon) { … }

Why does the first answer contain separation? Doesn't this lead to inaccurate results? For example (using prime numbers), let both $ a and $ b be 0.01, and suppose $ a - $ b results in 0.0001, with $ epsilon 0.001.

((((0.01 - 0.01) == 0.0001) / 0.01 == 0.01) < 0.001) : false

then

(((0.01 - 0.01) == 0.0001) < 0.001) : true

My math may be a little rusty, but what am I missing?

When should you use one formula over another?

+4
source share
3 answers

, , epsilon , .

:

function areEqual(float $a, float $b) : bool {
    return abs(($a - $b) / $b) < 0.00001;
}
areEqual(10000, 10000.01);
areEqual(0.0000001, 0);

: 0.00001 ; , . , $a $b , , $a $b. 10000 ( ), 0.0000001 , , , .

.

: , . , . , .. , -, , . , , 1, 0.00001.

: . , . 0, , , . , epsilon. , , (/ 0.0001 * 10000) (/ 10000, , , , 10000)

. abs($a - $b) , , & div; . , abs ($a - $b) / $b. "", 0.00001, , 0.00001, 0,001%.


, . , , / , , - , epsilon. , epsilon float.

, , . . ( ) , ​​ . , , , .

+3

. , , , ( , ) . , ( ), , , .

0

, . , , .

, 1e-300 2e-300 - ( IEE 754 64- ), 1e300 1e300 + 1e-300 .

0

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


All Articles