0

I was wondering about the way JavaScript handles floating points.

I.e. suppose I set 5 variables to (no decimal numbers):

var a = 1/2, b = 1/3, c = 1/12, d = 1/12, e = 0;

Is the sum of these guaranteed to be 1?

The attached answer does not answer my question, I want to distinguish declaring variables of decimal number with defining them as stated above (0.5 vs. 1/2)

  • 3
    Possible duplicate of [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Maxim Kukhtenkov Jun 01 '18 at 14:57
  • also see [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) this is not just a JS issues, it's around how computers deal with precision – Liam Jun 01 '18 at 15:51
  • It's a good job I didn't say "possible duplicate..." then isn't it @EricPostpischil – Liam Jun 04 '18 at 08:08

1 Answers1

0

No, the sum is not guaranteed to be one.

Floating-point operations produce approximations of real arithmetic. In binary-based floating-point, 1/2 will be exact, but 1/3 and 1/12 will be approximated, and the additions of values may introduce further approximations. The rounding errors in each operation are effectively random, so there is no guarantee they will cancel and produce a sum that is exactly one. (That is speaking generally; they may or may not produce one for the specific problem 1/2 + 1/3 + 1/12 + 1/12, in which case they should do so reliably when the same operations are repeated in the same order. But for similar problems generally, there is no guarantee.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312