1

I am doing some decimal multiplication that requires very high accuracy. For some strange reason, my code is a little inaccurate. Why is this happening?

Code:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    long double x=100, y=0.8;
    cout<<setprecision(100)<<x*y;
}

Output:

80.00000000000000444089209850062616169452667236328125

As you can see the first few digits are correct but the last few digits are wrong. This code is really simple and I think it has no errors. Can anybody tell me what is wrong?

Qiu YU
  • 517
  • 4
  • 20
  • 1
    `0.8` cannot be represented exactly as a floating point value, (because in binary 4/5 is an infinite fraction). So some inaccuracy is inevitable. – john Aug 11 '20 at 13:34
  • Ironically the inaccuracy results from the fact that you are doing *binary multiplication*, if you were doing decimal multiplication there would be no inaccuracy. But computers work in binary. – john Aug 11 '20 at 13:37
  • *For some strange reason,* -- FYI, that "strange reason" has been well-known by computer scientists for decades. See the duplicate link. – PaulMcKenzie Aug 11 '20 at 13:47
  • I understand now. Thanks for the help. – Qiu YU Aug 11 '20 at 13:48

0 Answers0