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

33,663

Solution 1

Because that's how floating-point is defined (more generally than just Javascript). See for example:

Crudely speaking, you could think of 1/0 as the limit of 1/x as x tends to zero (from the right). And 0/0 has no reasonable interpretation at all, hence NaN.

Solution 2

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.

Solution 3

I realize this is old, but I think it's important to note that in JS there is also a -0 which is different than 0 or +0 which makes this feature of JS much more logical than at first glance.

1 / 0 -> Infinity
1 / -0 -> -Infinity 

which logically makes sense since in calculus, the reason dividing by 0 is undefined is solely because the left limit goes to negative infinity and the right limit to positive infinity. Since the -0 and 0 are different objects in JS, it makes sense to apply the positive 0 to evaluate to positive Infinity and the negative 0 to evaluate to negative Infinity

This logic does not apply to 0/0, which is indeterminate. Unlike with 1/0, we can get two results taking limits by this method with 0/0

lim h->0(0/h) = 0
lim h->0(h/0) = Infinity

which of course is inconsistent, so it results in NaN

Share:
33,663
Bloodyaugust
Author by

Bloodyaugust

Working at L4 doing JavaScript, HTML, CSS, and C#. I also run an indie games company in my free time, check out http://synsugarstudio.com

Updated on July 16, 2022

Comments

  • Bloodyaugust
    Bloodyaugust almost 2 years

    It seems to me that the code

    console.log(1 / 0)
    

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

    console.log(0 / 0)
    

    does return NaN. Can someone help me to understand the reasoning for this functionality? Not only does it seem to be inconsistent, it also seems to be wrong, in the case of x / 0 where x !== 0