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;
}
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.
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.
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.