int s = (.7 * 3) + (.3 * 3) is 2 ?

Started by
60 comments, last by Zahlman 19 years, 8 months ago
keen, you're wrong, since .3 * 3 and .7 * 3 (- respectively 0.9 and 2.1) are having roundoff erros when saved in the binary system - both are periodic fractions.
Thus it can happen that its not 3 but e.g. 2.9999.
I do know that I don't know anything.
Advertisement
ok, you convinced me ;)
my bad
it was easy to try out with .7*4 since that would have yieled the same values if it was in that way
but
int main(){  int a,b;  float c;  a=((float)(.7 * 3)) + ((float)(.3 * 3));  b=((double)(.7 * 3)) + ((double)(.3 * 3));  c=(.7 * 3) + (.3 * 3);  printf("%i,%i,%f\n",a,b,c);}

gives
3,2,3.000000
so it's roundoff errors in double and not float that makes it
welcome to the world of misterious float-to-int casts...

and in more relevant, it's rounded in pretty random ways,and you should always expect that casting of nearly-integer valued floats to ints gives very undefined results.
Even if you do
int a=3.0;
int b=4.0;
int c=5.0;
etc.
some will round down..
the problem is flats cant really take most values. a float can be exactly 1, exactly 2, but not exactly 3, for example.

and values printed by printf are rounded down to some degree, so they are not an accurate representation of the actual number contained in the float. when it prints 3.000000, it might well actually be 2.9999999.

2^23 is 8388608, almost 8 digits of accuracy, whereas the printf representation only returns 7. printf cant print the last digit, because it cant be sure what value it really represents.
Why can't a float be exactly 3? It would seem that the precision bits could easilly hold 11000... with an exponent of ...0001, exactly representing 1.5 * 2^1 = 3. (Yes, I know there is an implied bit and a bias, but those have been left out for clarity's sake)
Quote:Original post by Eelco
the problem is flats cant really take most values. a float can be exactly 1, exactly 2, but not exactly 3, for example.
Floats can be exactly 3 as well. Floats can represent all whole numbers exactly as long as the number is small enough to fit in the mantissa.
Is this not why we put "f" after floating point numbers? Does that make it exactly the number you hard-code?
"Learn as though you would never be able to master it,
hold it as though you would be in fear of losing it" - Confucius
No. The 'f' in 3.0f stands for float. If you omit it (3.0) then you create a double constant.
Quote:
Nothing is 'exactly' in floating point math. If you want to write 0.9 exacly in FP mathy you need 'exactly' infinite digits


I dont understand why this is the case for rational numbers.
If it was an irrational number, then I see why you would need
"exactly infinite digits".

- prowst

This topic is closed to new replies.

Advertisement