double precision

I am trying to add a series of numbers of type double and there are always precision errors with double numbers. for example 2.2 is stored as 2.199999999999997645. How can any calculations be right if this happens. When a long series of calculations is done the error becomes dramatic and unacceptable. How do you deal with this?

Can anyone give me an answer on how to deal with this.

Here is a simple example of the problem.

#include <iostream>
using namespace std;

int main()
{
double x = 0.0;
double i;

for( i = 0.0; i < 100; i+= 0.1)
{
x = x + i;
cout.precision(16);
cout << fixed;
cout << i << " " << x << endl;
}

return 0;
}
Last edited on
In most scientific computing two floating-point numbers can be considered equal if the absolute value of their difference is less than a "small" number; say
abs(x-y) < eps;
with eps set to, say, 1.0e-10.

If you want no rounding errors then you need to compare integers, which are stored exactly.

The real world works the same way - you measure to a finite precision (and all length measurements change with temperature). Similarly, most mathematical functions are determined either by a finite number of iterations, or by a truncated sum of an infinite series.

As long as you are aware of the rounding possibility (particularly in if(..) statements) then this shouldn't cause problems.

You would need an awful lot of repeated calculations - with a highly-improbable repeated bias to one-sided rounding - for the difference you cite to become "dramatic and unacceptable".
Last edited on
Thanks for your input. I guess for situations dealing with money it takes a special class to deal with this problem.
Last edited on
For situations dealing with money, one could use integer values based upon the smallest unit of currency (such as cents or pennies). You would also observe specified rules on rounding - rather than let the default (truncation) occur, the rules specified by the business would be used. For particular calculations, such as interest etc., you might have additional requirements, again, the business requirements would give the rules.
Topic archived. No new replies allowed.