I have a Point3d class for which I created a scalar multiplication operator like so:

Point3d operator*(double mul) { return {x*mul, y*mul, z*mul}; }

This does not seem to multiply doubles correctly. In my testing when I multiply a Point3d object by 10^-6 and then check the x coordinate, I get .000002.

But, when multiplying the components by hand I get 2.1584e-06.

The former definitely only has 1 digit of precision because if the operator is too small the Point3d goes to 0.0. Why is this happening?

1 Answers

4
paxdiablo On Best Solutions

If you write them both out without an exponent, you see:

.000002
.0000021584

That means they're equal, to the point where the former stops. So it's almost certainly the printing of the value that's giving you your difference. Try it with something like:

#include <cstdio>
:
printf("%.20f\n", myDouble); // I can't be bothered looking up the iomanp stuff :-)

This should show you more than the default number of digits.