19.5 Roundoff Error

I l @ ve RuBoard

Floating point is not exact. Everyone knows that 1 + 1 is 2, but did you know that 1 / 3 + 1 / 3 does not = 2 / 3 ? This can be shown by the following floating-point calculations:

2 / 3 as floating point is 6.667E-1

1 / 3 as floating point is 3.333E-1

 +3.333E-1  +3.333E-1  _______________________ +6.666E-1, or 0.6666 

which is not:

 +6.667E-1 

Every computer has a similar problem with doing floating-point calculations. For example, the number 0.2 has no exact representation in binary floating point.

Floating point should never be used for money. Because we are used to dealing with dollars and cents , it is tempting to define the amount $1.98 as:

 float amount = 1.98; 

However, the more calculations you do with floating point, the bigger the roundoff error. Banks, credit cards, and the IRS tend to be very fussy about money. Giving the IRS a check that's almost right is not going to make them happy. Money should be stored as an integer number of pennies.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net