Floating-point statement - why do these “identical” arrays fail?

I am using assertSame () in PHPUnit to compare the database result with the expected values. The result is floating point numbers.

PHPUnit returns this message (but I do not see the differences):

Failed asserting that Array (
    '1_1' => 11.111111111111
    '1_2' => 33.333333333333
    '1_3' => 55.555555555556
    '1_4' => 0.0
    '1_5' => null
    '1_total' => 100.0
) is identical to Array (
    '1_1' => 11.111111111111
    '1_2' => 33.333333333333
    '1_3' => 55.555555555556
    '1_4' => 0.0
    '1_5' => null
    '1_total' => 100.0
)

Why is this happening with an error and what is the correct way to compare arrays of floating point values?

+4
source share
3 answers

assertEquals has the argument $ floating_delta for this type of event:

$this->assertEquals($expected_array, $actual_array, '', 0.00001);

PHPUnit docs

+12
source

- . print_r . , , , :

Failed asserting that Array (
    '1_1' => 11.1111111111110347
    '1_2' => 33.3333333333331678
    '1_3' => 55.5555555555562773
    '1_4' => 0.0
    '1_5' => null
    '1_total' => 100.0
) is identical to Array (
    '1_1' => 11.1111111111110346
    '1_2' => 33.3333333333331679
    '1_3' => 55.5555555555562771
    '1_4' => 0.0
    '1_5' => null
    '1_total' => 100.0
)

, , — .

if ($var == 0.005)     /* just plain wrong! */

if (abs ($var, 0.005) < 0.001)    /*  more correct  */

if (abs ($var, 0.005) < 0.0001)    /* maybe more correct, depending on application */

if (abs ($var, 0.005) < 0.0000001)    /* possibly more appropriate */
+1

If anyone has a better suggestion, I assume this is a floating point precision error and follow the recommendations of the PHP manual: do not compare floating directly for equality .

So, my own solution is to round the array values ​​before comparing.

0
source

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


All Articles