0

I want to understand why this for doesn't stop its execution to 10. See the code:

#include <stdio.h>

int main()
{
  float i;
  for (i = 0.0; i <= 10; i += 0.01)
    printf("Iteration %g\n", i);

  return 0;
}

The latest iterations are:

Iteration 9.96013
Iteration 9.97013
Iteration 9.98013
Iteration 9.99013

Why this behaviour ?

Kyrol
  • 3,475
  • 7
  • 34
  • 46
  • 4
    Please see [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Weather Vane Mar 09 '16 at 13:02
  • 1
    @WeatherVane Maybe could be used to flag as duplicate. – LPs Mar 09 '16 at 13:05
  • 2
    You accumulate rounding errors because you add a small number which is not exactly representable as a IEEE floating point number (0.01) many times to another float. Additionally you make an exact comparison which is almost always wrong with floating points. The detailed rules how to compute with and compare floating point numbers are difficult (and I don't know them). You can avoid accumulating rounding errors by obtaining the steps through multiplication: `for(int=0; i<101; i++) { printf("Iteration %lg\n", i*0.01);`. Comparisons usually involve FLT_EPSILON from `float.h`. – Peter - Reinstate Monica Mar 09 '16 at 13:05
  • As a comparison, you could try to add (1.0/128) 128 times... – Peter - Reinstate Monica Mar 09 '16 at 13:13
  • 2
    Another thing: Don't call floats `i`. Just don't ;-). – Peter - Reinstate Monica Mar 09 '16 at 13:14
  • 2
    Thinking in decimal: what happens if you add one third (0.333333~) 3 times? You don't get `1.0`. One hundredth is exactly representable in decimal (by definition) but one third is not. – Weather Vane Mar 09 '16 at 13:24
  • @PeterA.Schneider I find it in an example. I never do it ;) – Kyrol Mar 09 '16 at 16:06

2 Answers2

0

In the last iteration, you see Iteration 9.99013 because if the loop iterated again, i would equal 10.00013, which is greater than 10, your looping condition. The for loop only continues as long as the condition is satisfied.

As @WeatherVane pointed out, you should take a look at this question, which explains why you see the additional 0.00013 at the end of your i variable.

Community
  • 1
  • 1
TayTay
  • 6,882
  • 4
  • 44
  • 65
0

10.00013 <= 10 condition false so control goes out of for loop

Abhishek
  • 3,348
  • 3
  • 15
  • 34