0
#!/usr/bin/perl

  $a = 1;

  while ( $a <= 50 ) {
    print "$a\n";
    $a += 0.025;
  }

Very simple code.

But here is how the output looks like...

2.225
2.25
2.275
2.3
2.325
2.35
2.375
2.4
2.42499999999999
2.44999999999999
2.47499999999999
2.49999999999999
2.52499999999999
2.54999999999999
2.57499999999999

Everything was fine until 2.42499999999999.

4.32499999999999
4.34999999999999
4.37499999999999
4.4
4.425
4.45
4.475
4.5

Then back to normal.

And it keeps alternating between what one would expect, and being off by a small fraction.

What's causing this?

49.8249999999982
49.8499999999982
49.8749999999982
49.8999999999982
49.9249999999982
49.9499999999982
49.9749999999982
49.9999999999982
Friedrich
  • 41
  • 3
  • 1
    More information about rounding errors in [this](https://www.youtube.com/watch?v=LEFVQaSgJ60&ab_channel=CurtisPoe) talk. – Håkon Hægland Jul 24 '21 at 17:14
  • 3
    25/1000 is a periodic number in binary just like 1/3 is periodic in decimal. As such, saving it accurately as a floating point number would require inifite storage. Every time you add the value, you introduce a little bit of error. One alterative: `my $x = 1000; while ($x < 50_000) { say $x/1000; $x += 25; }` – ikegami Jul 24 '21 at 21:25

0 Answers0