2

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?

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 2
    Can you explain how the linked question is related to my issue? – user2994612 May 04 '19 at 03:53
  • I don't believe it is related myself, which is why I voted to re-open :-) This is less of a floating point limited-precision issue and more of a *printing* issue. – paxdiablo May 04 '19 at 03:56

1 Answers1

4

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953