Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP for loop displaying strange results

Tags:

php

for-loop

I have this code:

for($i = 1; $i <= $max; $i+=0.1) {
    echo "$i<br>";
}

if the variable $max = 6; the results are: 1, 1.1, 1.2, 1.3 .... 5.8, 5.9, 6 , but when the variable $max = 4 the results are: 1, 1.1 ... 3.8, 3.9, but the number 4 is missing.

Please explain this behavior, and a possible solution to this.

the results are the same when i use the condition $i <= $max; or $i < $max;

The bug occurs when $max is 2, 3 or 4

like image 335
Gergely Králik Avatar asked Jan 14 '23 00:01

Gergely Králik


1 Answers

From http://php.net/manual/en/language.types.float.php

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision.

So to overcome this you could multiply your numbers by 10. So $max is 40 or 60.

for($i = 10; $i <= $max; $i+=1) {
    echo ($i/10).'<br>';
}
like image 59
bitWorking Avatar answered Jan 16 '23 02:01

bitWorking