c++ (about double and float)
Some asked me a question about a surpassingly bug in vc++. The original code looked like this:
double index;
for(index=0.0;index<1.0;index+=0.1)
cout<<(int)(index*10.0)<<endl;
//should print 0 1 2 3 4 5 6 7 8 9, but prints 0 1 2 3 4 5 6 7 7 9 9
I changed double to a float:
float index;
for(index=0.0;index<1.0;index+=0.1)
cout<<(int)(index*10.0)<<endl;
return 0;
and all went well, I don’t remember the exact reason ( the way float and double resides in memory + conversion issues to an int) but it's obviously not a bug.
Comments
- Anonymous
December 07, 2003
>//should print 0 1 2 3 4 5 6 7 8 9, but prints 0 1 2 3 4 5 6 7 7 9 9
Why "should" it print that?
Eric Gunnerson recently posted a link to an article on "what every computer scientist should know about floating point arithmetic":
http://blogs.gotdotnet.com/EricGu/permalink.aspx/8dc27f6a-2094-40a4-b5c0-ca92a718a7ee - Anonymous
December 07, 2003
I think it's an issue with the double 'addition' - there is a very small value (DBL_EPS?) which is defined in 'limits.h' that addresses it. Basically, 1.0+DBL_EPS is <> 1.0.. So the correction would have to be in the increment counter of the 'for loop'.. - Anonymous
December 07, 2003
Addendum - the increment counter and the condition for loop exit..