简体   繁体   中英

When does a floating point number overflow?

Why is

Number.MAX_VALUE + Number.MAX_VALUE == Number.MAX_VALUE
=> false

but

Number.MAX_VALUE + Number.MIN_VALUE == Number.MAX_VALUE
=> true

?

My expectation was, that everything I add to the maximum value must overflow.

Imagine it like this:

MAX_VALUE = Infinite

MIN_VALUE = 0

So, when you add MAX_VALUE with MIN_VALUE it's like you added 0. So it's still MAX_VALUE.

Think of it as all the non-zero digits being far, far to the right, and therefore they have no net effect.

JavaScript's Number.MAX_VALUE is misnamed. It is not the maximum representable value. It is the maximum representable finite value. The actual maximum representable value is infinity.

If the name were correct, so that Number.MAX_VALUE were infinity, then Number.MAX_VALUE + Number.MAX_VALUE == Number.MAX_VALUE would be true, because infinity plus infinity is true.

As it is the mathematical value of Number.MAX_VALUE + Number.MAX_VALUE is beyond the representable finite values, so it is rounded to infinity.

Number.MAX_VALUE + Number.MIN_VALUE == Number.MAX_VALUE is true because arithmetic rounds to the nearest representable value, and adding a small value to the maximum finite value produces a result very close to the maximum finite value, so it rounds to the maximum finite value.

(Note: The rule about rounding to the nearest representable value treats infinity as if it were in a normal place at the end of the finite values, so any result that is greater than or equal to Number.MAX_VALUE plus half a “step” beyond it rounds to infinity.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM