C++ floating point precision

Davinel picture Davinel · May 26, 2010 · Viewed 49.9k times · Source

Possible Duplicate:
Floating point inaccuracy examples

double a = 0.3;
std::cout.precision(20);
std::cout << a << std::endl;

result: 0.2999999999999999889

double a, b;
a = 0.3;
b = 0;
for (char i = 1; i <= 50; i++) {
  b = b + a;
};
std::cout.precision(20);
std::cout << b << std::endl;

result: 15.000000000000014211

So.. 'a' is smaller than it should be. But if we take 'a' 50 times - result will be bigger than it should be.

Why is this? And how to get correct result in this case?

Answer

Cubbi picture Cubbi · May 26, 2010

To get the correct results, don't set precision greater than available for this numeric type:

#include <iostream>
#include <limits>
int main()
{
        double a = 0.3;
        std::cout.precision(std::numeric_limits<double>::digits10);
        std::cout << a << std::endl;
        double b = 0;
        for (char i = 1; i <= 50; i++) {
                  b = b + a;
        };
        std::cout.precision(std::numeric_limits<double>::digits10);
        std::cout << b << std::endl;
}

Although if that loop runs for 5000 iterations instead of 50, the accumulated error will show up even with this approach -- it's just how floating-point numbers work.