-3

Hi this is surely simple but i cant find the answer to why this doesn't quit the loop after 0.9

    #include <stdio.h>

    int main()
    {
            float x;
            for(x=.1;x!=1.0;x+=.1)
            printf("%f\n", x);
            return 0;
    }
Leo
  • 11
  • 2
  • did you try a while loop? Or try x < 1.0 and see what happens. – Atieh Sep 06 '14 at 04:29
  • 1
    A simple search on SO for "floating point equality" probably returns hundreds of results. Also, [this](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – vanza Sep 06 '14 at 04:40
  • http://stackoverflow.com/questions/13577689/why-double-plus-sometimes-right-sometimes-wrong?rq=1 http://stackoverflow.com/questions/588004/is-floating-point-math-broken http://stackoverflow.com/questions/22791764/c-c-1-00000-1-0f-false there are hundreds of duplicates here, do a search first – phuclv Sep 06 '14 at 04:52
  • http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – phuclv Sep 06 '14 at 04:53

2 Answers2

3

For your code to work, this

float x;
for(x=.1;x!=1.0;x+=.1)
  printf("%f\n", x);
return 0;

Needs to be something like

float x;
for(x=.1;x < 1.0;x+=.1)
  printf("%f\n", x);
return 0;

The explanation is the representation of floating point numbers in IEE-754, in base 2 1/5 is a recurring fraction - and that isn't precisely representable so it's rounded.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

When a computer tries to represent 0.1 as a floating point, it uses base 2. However, this does not allow an exact representation of 0.1, only an approximate one. When the 10th iteration is reached, you have something very close to 1.0, but not exactly. This causes the != to evaluate to true, and the loop keeps going. Change it from != to <, and it will run correctly. See the link in Elliott Frisch's answer for more information.

McLovin
  • 3,554
  • 1
  • 14
  • 15
  • 1
    Why the -1? This answer is simple, concise, truthful, and it speaks directly to the question. The only thing is leaves out is that 1.0 _does_ have an exact representation in base 2, and so ten _inexact_ 0.1's do not add up to one exact 1.0. – Solomon Slow Sep 06 '14 at 19:08