I ran into a floating point error today (verified in JavaScript and Python) that seems peculiar.
> 15 * 19.22
288.29999999999995
What really weird about this scenario is that these numbers are well within the range of numbers representable by floating point. We're not dealing with really large or really small numbers.
In fact, if I simply move the decimal points around, I get the correct answer without rounding error.
> 15 * 19.22
288.29999999999995
> 1.5 * 192.2
288.29999999999995
> .15 * 1922.
288.3
> 150 * 1.922
288.3
> 1500 * .1922
288.3
> 15 * 1922 / 100
288.3
> 1.5 * 1.922 * 100
288.3
> 1.5 * .1922 * 1000
288.3
> .15 * .1922 * 10000
288.3
Clearly there must be some intermediate number that isn't representable with floating point, but how is that possible?
Is there a "safer" way of multiplying floating point numbers to prevent this issue? I figured that if the numbers were of the same order of magnitude, then floating point multiplication would work the most accurately but clearly that is a wrong assumption.