1

I just found an arithmetic bug that, very simplified, when multiplying two numbers and then dividing, the order of operations give different values!

In this case, multiplying first gives the correct answer:

(1455/1279) * 1279
1455.0000000000002
(1455*1279) / 1279
1455

I can see that the larger numerator might be advantageous, but it too could have problems, overflow for example.

So the question is: why does this occur, and what are the best practices for JavaScript numeric operations?

backspaces
  • 3,802
  • 6
  • 34
  • 58
  • the rule of thumb is, to keep as along as it goes an integer value and then take a divison. – Nina Scholz Jul 07 '19 at 16:33
  • 1
    Double-precision floating-point format can store about 15.95 significant digits https://en.wikipedia.org/wiki/IEEE_754#Basic_and_interchange_formats, so start with the operation that would result in less digits. There can be loss of precision from multiplying or addition of very big numbers too if the result is above 15.95 digits – Slai Jul 07 '19 at 16:50
  • There is no overflow exception, but result is `Infinity` when the number is around `2 * Number.MAX_VALUE`, and 0 when the number is around `1 / (2 * Number.MAX_VALUE)` – Slai Jul 07 '19 at 16:59

0 Answers0