Subject: Another floating-point riddle

From: "Nadav Har'El" <[email-masked]>
Date: Wed, 22 Nov 2000 16:01:00 +0200

Here's another floating-point-related riddle.
Take a look at the following program:

main(){
        int i;
        double d=0.2;
        for(i=0;i<100;i++){
                d*=2;
                if(d>1)
                        d--;
        }
	printf("%g\n",d);
}

What is the number it will print? Thinking about it theoretically for a
moment, you see that the d sequence is 0.2, 0.4, 0.8, 0.6 and then returns
to 0.2 and repeats again, so you'd expect to see one of these numbers
as the last number. But try running this program (on any "typical" computer),
and you'll be surprised: the answer is 1.0!
The question is to try to explain why.

-- 
Nadav Har'El                        |  Wednesday, Nov 22 2000, 24 Heshvan 5761
[email-masked]             |-----------------------------------------
Phone: +972-53-245868, ICQ 13349191 |I intend to live forever - so far, so
http://nadav.harel.org.il           |good.