4

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

3
  • I think this has something to do with roundoff problems: docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html In fact, the error is not the missing 4 but the printed 6 Commented Jun 29, 2013 at 11:54
  • 2
    read the red block about Floating point precision. Floating point numbers Commented Jun 29, 2013 at 11:56
  • 1
    if i modify the loop 'for($i = 1; $i <= $max; $i+=0.1)' the problem remains the same Commented Jun 29, 2013 at 11:57

4 Answers 4

4

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>';
}
Sign up to request clarification or add additional context in comments.

Comments

2
$err = .000001//allowable error
for($i = 1; $i <= $max+$err; $i+=0.1) {
    echo "$i<br>";
}

Comments

2
  You can use of number_format()

<?php
$max=6;
for($i = 1; number_format($i,2) < number_format($max,2); $i+=0.1) {
echo $i."<br>";     
}

?>

1 Comment

set $max = 100 and see what happens. The rounding error starts at 54.2 in my case.
1

You should set the precision when using integers,

like this:

$e = 0.0001;
   while($i > 0) {
   echo($i);
   $i--;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.