r/programming • • Jun 28 '21

JavaScript Is Weird

https://jsisweird.com/
329 Upvotes

173 comments sorted by

View all comments

Show parent comments

12

u/stalefishies Jun 28 '21

Right, and that's why 0/0 is undefined instead of Infinity.

NaN is not 'undefined'. It is a well-defined possible value that a floating-point type can take. If 0/0 were truly undefined, then the entire program would become meaningless as soon as that expression was evaluated. That's the case in mathematics: if you have 0/0 appear in a mathematic proof (and you've not taken great pains to define exactly what that means) then your proof is meaningless. That's not true in JavaScript: if you have 0/0 appear, it just evaluates to an appropriate NaN and execution continues.

Regardless, there's no floating point arithmetic going on in that example.

Yes there is. Writing 0/0 in JavaScript is a double-precision floating-point operation. It is the division of positive zero by positive zero.

0

u/[deleted] Jun 28 '21

Writing 0/0 in JavaScript is a double-precision floating-point operation. It is the division of positive zero by positive zero.

The point is it's not actually doing ANY FP arithmetic. There's zero oddness arising from loss of precision or other weird quirks of the actual arithmetic as in the others. If you could perfectly describe the behavior of FP numbers in a computer, you'd still have the exact same problem.

5

u/stalefishies Jun 28 '21

No, there's a very fundamental difference between 0/0 in the mathematics of real numbers, where such an object just does not exist, and in floating-point arithmetic, where it evaluates to NaN which is simply one possible value a floating-point number can take, and is not fundamentally different to 0.0 or 1.0 or infinity. NaN is not some 'error', it is really (despite its name) just another number. That only comes from the way floating-point is defined, not from any fundamental mathematical truth.

0

u/Rzah Jun 28 '21

Are you saying that javascript actually calculates 0/0 rather than recognising it as a special case and returning NaN?

→ More replies (0)