Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP anomaly/ weird behaviour

When I run:

for($o=1;$o<=655;$o++){ $r = $r+0.01; echo $r." ";}

at some point I get:

...4.29 4.3 4.31 4.32 4.33 4.34 4.35 4.36 4.37 4.38 4.39 4.4
4.41 4.42 4.4299999999999 4.4399999999999 4.4499999999999
4.4599999999999 4.4699999999999 ...

But when I run:

for($o=1;$o<=5;$o+=0.01){ echo $o." "; }

anomaly starts at:

4.34 4.35 4.36 4.37 4.38 4.3899999999999 4.3999999999999

Why is there a difference between the addition being part of the for loop, or within the for loop?

like image 631
meso_2600 Avatar asked Dec 31 '25 00:12

meso_2600


1 Answers

Welcome to the wonders of rounding errors.

0.01 is not exactly expressible as a finite binary fraction, so you'll pick up rounding errors eventually if you add it repeatedly to another floating point number.

The specific point at which you see the rounding error depends on how the binary expansion of the numbers involved play out to produce the rounding error.

like image 84
John Avatar answered Jan 04 '26 16:01

John



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!