0

i'm following a course of Computer Architecture and our teacher gave us the code below and told us to execute it, so we can comment on it together in class, but, I can't understand why it creates an endless loop. I would love if someone more experienced could help. Thank you!

#include <stdio.h>

int main() {

float x = 0.1;

while (x!=1.1) {
   printf("x = %f\n", x);
   x = x + 0.1;
}

return 1;
}
  • [Is floating point math broken?](//stackoverflow.com/q/588004) – 001 Oct 24 '18 at 20:11
  • Just to add to the above, you'd want to use an inequality comparison when dealing with those scenarios, so `while (x < 1.1) {...}` might be a bit better, but once `x` is close to `1.1`, it may or may not iterate one more time. – frslm Oct 24 '18 at 20:14
  • 1
    `0.1` *cannot* be represented exactly in any floating point format; the closest representable value is a little above that. So after 10 additions, what you have in `x` is not `1.1`. Since `x` is never exactly equal to `1.1`, the loop never terminates. – John Bode Oct 24 '18 at 20:15
  • 1
    *Using a floating number as a loop counter* -- don't. – Christian Gibbons Oct 24 '18 at 20:16
  • 1
    don't compare for equality with floating point numbers - it's a recipe for disaster. You can use < and > where that makes sense. – xaxxon Oct 24 '18 at 20:18
  • @JohnBode I am not sure, but wouldn't the `1.1` constant "rounded" by the compiler towards the closest representable one (representable in `double`, though, but still)? – Eugene Sh. Oct 24 '18 at 20:21
  • @JohnBode: 0.1 can be represented exactly in a decimal floating-point format, such as the ones specified in IEEE-754. “Floating point” does not mean “binary”; it means the point floats (*i.e.*, the value is scaled by a power of some base). Intel and IBM make compilers and processors with support for decimal floating-point, and there are software decimal floating-point implementations in various applications. – Eric Postpischil Oct 24 '18 at 20:29
  • @EugeneSh.: `1.1` in source code is (usually) converted to `double` by rounding to the nearest representable value. But the result of adding eleven instances of `0.1` is different. First `0.1` is converted to the nearest representable value, and then ten additions are performed. In each addition, the mathematical result is rounded to the nearest representable value. Sometimes these produce roundings up, sometimes down, sometimes none. The final result may differ from the result of converting `1.1` to the nearest representable value. – Eric Postpischil Oct 24 '18 at 20:32
  • @EricPostpischil Yeah, this is what I meant, to point that the problem is originating from the addition rather than from the comparison only. – Eugene Sh. Oct 24 '18 at 20:36

0 Answers0