Search code examples
c++loopswhile-looptermination

while loop doesn't terminate properly


I suspect this might have something to do with rounding errors since I'm using doubles to control the loop termination, but I'd like to really know what's going on

#include<iostream>

using namespace std;

int main()
{
  double h = 0.2;  // stepsize                                                                                                                                                                       
  double t_0 = 1;
  double t_n = 25;
  double y_0 = 1;  // initial condition                                                                                                                                                              


  double t = t_0;
  while(t < t_n)
    {
      cout << "t: " << t << endl;
      cout << "(t < t_n): " << (t < t_n) << endl;
      t += h;
    }
}

The last few lines of output are

t: 24.4
(t < t_n): 1
t: 24.6
(t < t_n): 1
t: 24.8
(t < t_n): 1
t: 25
(t < t_n): 1

Shouldn't the last statement return false? I.e., shouldn't the loop terminate @ 24.8?


Solution

  • The reason this does not work is that 0.2 cannot be represented precisely in a float, because its fractional part is not an exact sum of negative powers of two. If you try it with a different number, say, 0.25, the code will work, because 0.25 is 2^-2.