range(-8.00, 8.00, 0.05) acting very strange

后端 未结 3 458
迷失自我
迷失自我 2021-01-13 17:16

Does anyone know why range(-8.00, 8.00, 0.05) seems fail?

Array
(
[0] => -8
[1] => -7.95
[2] => -7.9
[3] => -7.85
[4] => -7.8
[5] => -7.75
         


        
相关标签:
3条回答
  • 2021-01-13 17:44

    That's a known problem, hopefully already fixed. See bug #54459.

    Basically now instead of making consecutive floating point additions, the range function now increments an integer and multiplies it by the step.

    Basically, you know have:

    -8.00, -8.00 + 1 * 0.05, -8.00 + 2 * 0.05, ...
    

    instead of

    -8.00, -8.00 + 0.05, -8.00 + 0.05 + 0.05, ...
    

    You can see this makes a difference:

    $ php
    <?php
    for ($i = 0; $i < 9.99; $i += .1) {}
    echo sprintf("%.17f", $i);
    ^D
    9.99999999999998046
    

    while:

    $ php -r 'echo sprintf("%.17f", .1*100);'
    10.00000000000000000
    
    0 讨论(0)
  • 2021-01-13 17:46

    You may want to try a range between 800 and -800 with steps of 5 and then add in the decimal points / divide by 100 afterward.

    0 讨论(0)
  • 2021-01-13 17:58

    That would be because floating point numbers are not precise and not all numbers can be represented exactly using floats.

    0 讨论(0)
提交回复
热议问题