0
for(float i=1; i<=1.5; i+=0.1) 
{
  // statements
}

The above C++ for loop runs for 5 times. Shouldn't this run for 6 times?

Shwetha
  • 25
  • 1

2 Answers2

2

This is a great example of a floating point precision error. Precise values like multiples of 0.1, 0.2 cannot be precisely represented internally in the computer's memory. You'll want to do a comparison using EPSILON (http://en.cppreference.com/w/cpp/types/numeric_limits/epsilon)

Something like

for (float i = 1; fabs(1.5 - i) < EPSILON; i+=0.1) {
  //statements
}
CollinD
  • 7,304
  • 2
  • 22
  • 45
0

It is because multiples of 0.1 cannot be presented precisely in binary, and the actual value stored is an approximation that may be slightly less than 0.1. So, 5*0.1 might be less than 0.5 or it might be more (depending on how the floating point values are represented).

It is usually a really bad idea to use a floating point variable (and tests involving equality or inequality of floating point values) to control loops at all. Effects can include running more (or less) times that intended, or - in some bad cases - an infinite loop where a finite number of runs was expected.

In your case, you would be better off doing something like

for (int i = 0; i < 5; ++i)
{
     float value = 1.0 * i*0.1;
       // use value here rather than the i in your original code
}

Alternatively, you can use some test that allows for the imprecision of floating point (e.g. compare i - 1.5 with some value such as machine epsilon). The catch with this is that the actual number of iterations still potentially has some level of unpredictability, particularly in loops that involve a large number of iterations (e.g. iterating from 1.0 to 50000.0 in steps of 0.01) because rounding errors can either accumulate or cancel out at different stages during the loop.

Peter
  • 35,646
  • 4
  • 32
  • 74