Why does multiplying two large double numbers give

2019-06-14 17:40发布

问题:

The output for this double multiplication (double)1000000007 * (double)11111111 should end with 7 (or equal to 11111111077777777 be precise). But this piece of code I wrote outputs the result ending with 6 (or equal to 11111111077777776 to be precise). I cannot figure out what I might be doing wrong. Any help would be great.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    cout << setprecision(40) << (double)1000000007 * (double)11111111;
}

回答1:

When you do multiplication with double values, the results are not precise. There is an inherent precision available to double, which, while fairly accurate, is not precise enough to exactly represent your value.

I recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic.



回答2:

Floating point math isn't exact, it's just very accurate. I encourage you to read about it here: http://en.wikipedia.org/wiki/Floating_point

Basically there aren't enough bits to exactly represent that number, so you get precision errors.



回答3:

You are doing nothing wrong. It has to do with the implementation of doubles. If you need accuracy beyond what the implementation of doubles provides, there are surely libraries available for "big number" operations.



标签: c++ double