In JavaScript, why does zero divided by zero return NaN, but any other divided by zero return Infinity?

前端 未结 3 1097
清酒与你
清酒与你 2020-11-29 07:53

It seems to me that the code

console.log(1 / 0)

should return NaN, but instead it returns Infinity. However this

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 08:46

    In addition to answers based on the mathematical concept of zero, there is a special consideration for floating point numbers. Every underflow result, every non-zero number whose absolute magnitude is too small to represent as a non-zero number, is represented as zero.

    0/0 may really be 1e-500/1e-600, or 1e-600/1e-500, or many other ratios of very small values.

    The actual ratio could be anything, so there is no meaningful numerical answer, and the result should be a NaN.

    Now consider 1/0. It does not matter whether the 0 represents 1e-500 or 1e-600. Regardless, the division would overflow and the correct result is the value used to represent overflows, Infinity.

提交回复
热议问题