0

This is an example of my code:

float a = 0.f;
float b = 5.f;
float increment = 0.1f;
while(a != b)
    a+=increment;

This will result in an infinite loop. Is there any solutions to it, or the only way to solve this is to set a tolerance?

Uytab
  • 85
  • 1
  • 7
  • 1
    [Relevant](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Cory Kramer May 28 '21 at 13:51
  • In general, yes a tolerance could help `while (std::fabs(b-a) < 1.0e-6)` or whatever – Cory Kramer May 28 '21 at 13:52
  • In general, by whatever means, always use integer as the looping condition. If you know you must loop `n` times, then loop `n` times, then figure out any floating point within the loop. – PaulMcKenzie May 28 '21 at 14:07
  • In general, loop termination conditions that depend on incrementing numeric values ought to be written with `<` rather than `!=`. That avoids this kind of problem. `while (a < b)` is not an infinite loop. – Pete Becker May 28 '21 at 15:25

1 Answers1

6

Avoid using floating-point calculation when possible. In this case you can treat with the numbers as integer by multiplying them by 10 and dividing by 10 in the end.

float a, b, increment;
int a_i = 0;
int b_i = 50;
int increment_i = 1;
while(a_i != b_i)
    a_i+=increment_i;
a = a_i / 10.f,
b = b_i / 10.f;
increment = increment_i / 10.f;
MikeCAT
  • 73,922
  • 11
  • 45
  • 70