Is complement commutative?

JavaScript numbers are fancy. I realized that the addition is not associative:

(-9999999999999999 + 1) + 1 === -9999999999999999 + (1 + 1) // false!

      

How about commutability? Do JavaScript numbers exist a

, b

such that

typeof a === 'number'
typeof b === 'number'
a + b !== b + a

      

are all evaluated before true

(except NaN

)?

+3


source to share


1 answer


If you look closer, you can see that 1-9999999999999999 returns -10000000000000000, which is not the result of this operation (it should be -9999999999999998) You are just hitting the floating point precision limit. You can see the same effect with this: 0.0000000000000001 + 1 and 0.0000000000000002 + 1

So the ecmascript specification , the numbers must be IEEE 754 64-bit. This corresponds to 16-digit precision. It is the size of your numbers.

EDIT

As for your question about commutability, here's what the spec says:

In other cases, when neither infinity, nor zero, nor NaN are involved, and the operands have the same sign or have different values, the sum is calculated and rounded to the nearest representable value using the IEEE 754 circular section, to the nearest mode. If the value is too large to be represented, the operation overflows and the result is infinity of the appropriate sign. ECMAScript requires gradual overflow support as defined in IEEE 754.



Therefore, it should always be commutative as the sum is calculated and then rounded. Any other behavior will be your browser's fault.

EDIT 2

It is even clearer that the specification explicitly states (section 11.6.3):

Complement is a commutative operation, but not always associative.

+2


source







All Articles