Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 264
Bloodyaugust Avatar asked Sep 16 '13 22:09

Bloodyaugust


People also ask

Why is 0 divided BY 0 NaN?

In IEEE 754 arithmetic, a ÷ +0 is positive infinity when a is positive, negative infinity when a is negative, and NaN when a = ±0. The infinity signs change when dividing by −0 instead. The justification for this definition is to preserve the sign of the result in case of arithmetic underflow.

What happens if you divide by 0 in JavaScript?

The output of the code in JavaScript is as follows: Dividing the number 0 by 0 returns NaN. Dividing the positive number by 0 returns Infinity. Dividing the negative number by 0 returns -Infinity.

Why is 1 0 Infinity in JavaScript?

It is greater than any other value, and you can get it by dividing by 0 or by evaluating the expression of a number that's so big that overflows. This actually means there is no division by 0 errors in JavaScript, there is Infinity!


1 Answers

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

  • http://en.wikipedia.org/wiki/Floating-point#Infinities
  • http://en.wikipedia.org/wiki/NaN#Creation

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.

like image 52
Oliver Charlesworth Avatar answered Oct 20 '22 14:10

Oliver Charlesworth