# Floating Point Accuracy...

• 10-17-2006
The SharK
Floating Point Accuracy...
I just wonder:

When I run this program, why is it that the result is a little incorrect ?
Like 0.2 * 1 == 0.20000000000000001
and
0.2 * 2 == 0.40000000000000002
• 10-17-2006
swgh
Why not tell the compiler to show the decimal two spaces from the decimal point using set precision?

Code:

```#include <iostream> using std::fixed; using std::cout; #include <iomanip> using std::setprecision; int main ( void ) {   double val = 5.5;   double res = val + val;   cout << Result:  " << fixed << setprecision( 2 )  << res;   return 0; }```
• 10-17-2006
The SharK
Hi swgh

Sure I could !

But that didn't answer the question... ;-)

regards,

The SharK
• 10-17-2006
Frobozz
Floating point numbers in computers are never going to be infinitely precise. To have that level of precision would require unlimited memory. If my memory is right, single-precision numbers are accurate to seven decimal places while double-precision are accurate to fifteen.
• 10-17-2006
The SharK
I see, thanks Frobozz ;-)
• 10-17-2006
Dweia
Single precision is 24 bits of precision (including leading 1) while double is 53, which yes, works out to about 7 and 15 decimal places
• 10-17-2006
maxorator
And that's all the accuracy computers provide us :(
• 10-17-2006
Salem
http://en.wikipedia.org/wiki/IEEE_fl...point_standard
Especially read David Goldberg's paper at the end
• 10-17-2006
jafet
You could use BCD instead of binary if you want decimal precision ie. storing the number as base 10 digits instead of base 2 bits.
• 10-17-2006
Salem
• 10-18-2006
grumpy
Quote:

Originally Posted by jafet
You could use BCD instead of binary if you want decimal precision ie. storing the number as base 10 digits instead of base 2 bits.

That doesn't eliminate the problem. Try to compute 1/7 (as a real value, not using integer arithmetic) and store than within a finite number of decimal places.