0

Can some enlighten me with the multiplication behavior using double datatype in c++? In an example program below, I have three variables (x,y,z) of type double. when I multiply these variables the products are different depending on the order. Keep in mind the values I'm using in the example are my sample computational values.

void main()
{
    double x, y, z;
    double prod1, prod2;

    x = 8.3832170034737544e-05;
    y = 5.6690000000000000e-08;
    z = 0.29999999999999999;

    prod1 = x*y*z;
    prod2 = y*z*x;

}

results:

prod1 : 1.4257337157807814e-12
prod2 : 1.4257337157807812e-12

In the example above, results for both prod1 and prod2 are different. How can I fix this issue in which I can always have the same result whatever the order of (x,y,z) is and using the exact same values.

ralpu
  • 193
  • 3
  • 15
  • 1
    A double is only good to about 15 digits. After that you get fuzz that you're better off ignoring. And sure enough the difference is about 16 digits down. You can't win this fight, so don't worry about it. – user4581301 Jan 04 '18 at 04:48
  • This is a property of floating-point arithmetic. You can't "fix" it. – molbdnilo Jan 04 '18 at 08:20

1 Answers1

0

Because of the precision of floating point type.

double guarantees precision 15 decimal places.

You can use long double type if you like. but it is not mandated by IEEE-754

#include <iostream>

int main(void)
{
    long double x, y, z;
    long double prod1, prod2;

    x = 8.3832170034737544e-05;
    y = 5.6690000000000000e-08;
    z = 0.29999999999999999;

    prod1 = x*y*z;
    prod2 = y*z*x;

    std::cout.precision(17);
    std::cout << prod1 << std::endl;
    std::cout << prod2 << std::endl;

    return 0;
}

result

1.4257337157807814e-12
1.4257337157807814e-12
  • 1
    That doesn't solve anything. It just kicks the problem 'down the road' (so to speak). I.e. Same problem can be produced at higher precision with different values. OP needs to learn and understand the principles of floating point math. – Disillusioned Jan 04 '18 at 23:29