Floating Point Approximations.



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.




.



Relevant Pages

  • Re: static_cast<unsigned int> question...
    ... > unsigned int test2; ... This is caused by the way the float type store number internally. ... floating point value to: ... This is also the reason why comparing two floating point values with the ...
    (comp.lang.cpp)
  • Re: 0.0 versus 0.0f
    ... You said it treats it as a float rather than an int. ... the Microsoft C compiler does not complain about ... integer or floating point. ...
    (microsoft.public.vc.mfc)
  • Re: 0 converted to 0.0 for float variable?
    ... will C automatically add a decimal point and at least one zero to the ... the statement involves a float ... variable and an int value. ... to something in your source code; ...
    (comp.lang.c)
  • Re: Bug in conversion to ingegers???
    ... 0.01F cannot be exactly represented as a floating point number. ... As far as I can tell, the multiplcation is done using doubles, so ... float range, which in this case, is 1. ... However, when you cast it directly to an int, the decimal portion is ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Interesting math
    ... precision when a number is zero. ... A C Float Number must have six or more significant digits ... and read about C Float Numbers and programming in C language. ...
    (alt.usage.english)