# Re: Floating Point Approximations.

Date: Thu, 29 Mar 2007 08:22:37 GMT

Message-ID: <hHKOh.10603$Qi2.8732_at_trndny07>

"David Cressey" <cressey73_at_verizon.net> wrote in message
news:QXuOh.4210$5E3.2288_at_trndny01...

> Here's another example of floating point errors, that's even simpler than

*> the 21200 plus 2.5% example.
**>
**> int i;
**> float x = 0;
**> for (i = 1; i < 100; ++i)
**> x += 0.01;
**> x -= 1;
**> printf (x);
**>
**> I apologize if I copied the code wrong. The idea is to start with zero,
**> add one hundredth a hundred times, and subtract one. The answer is not
**> quite zero.
**>
**>
**>
**> Many environments will give a small error. This is such a trivial example
**> that it should make all programmers shudder about using floats, unless
*

they

> really know what they are doing.

*>
**>
**>
*

Arrrgh! I knew that it was a pitfall to copy this code from memory. But
it's particularly embarassing to have made a fencepost error. Of course,
the example in the book reads:

*> int i;
**> float x = 0;
**> for (i = 0; i < 100; ++i)
**> x += 0.01;
*

> x -= 1;

*> printf (x);
**>
*

I actually ran it, and the answer it gives is a very small non zero number.

*>
*

Received on Thu Mar 29 2007 - 10:22:37 CEST