-
July 19th, 2004, 10:06 AM
#1
question: double C++
why is: dA(=200.9) - sSub(=100.3) != dB(=100.6)
double dA=200.9, dSub=100.3;
double dB=100.6;
if( dA-dSub == dB)
int x=1;
else
int Y=1;
-
July 19th, 2004, 10:17 AM
#2
That is because 200.9 can't be represented exactly on a double. dA will be 200.90000000000001. You can guess the rest...
The morale is: never use == on floating point results as condition for branches or loops...
-
July 19th, 2004, 10:26 AM
#3
could you explain to me in details why 200.9 can't be represented exactly on a double
-
July 19th, 2004, 10:53 AM
#4
Originally Posted by Christian Hofner
could you explain to me in details why 200.9 can't be represented exactly on a double
This paper explains it pretty well...
-
July 19th, 2004, 11:05 AM
#5
Originally Posted by Christian Hofner
could you explain to me in details why 200.9 can't be represented exactly on a double
Not to get into floating point representations such as IEEE, but the simplest answer is for you to try and convert 0.9 to binary. You will see that when it is converted, you get a repeating, non-terminating binary floating point number, while 0.9 is a terminating, non-repeating, decimal number.
0.9 (decimal) = 0.11100110110110110....110... (binary)
This is basically the same reason why "1 / 3 * 3" is 0.9999999 on some of the older hand calculators, when mathematically it should be 1.0000000 in that "1/3" cannot be represented exactly as a floating point number in binary. Unless the decimal floating point number is a sum of inverse powers of 2 (for example 1/2, 1/4, 1/8, 1/16, etc.) then the decimal number cannot be represented exactly in binary.
Of course, there are processors that handle a lot of these "inexact" issues, but they are not 100% perfect, as you can see from your program. It still boils down to the fact that decimal values cannot be represented exactly as binary values (not counting the case I mentioned above with the inverse powers of 2).
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|