一些实验
我打算用 JS 编写一些数学表达式,我想知道:
typeof(Infinity) // "number", in Maths it is NOT a number
typeof(NaN) // "number", how NaN (Not A Number) can actually be a number?
还有一些实验:
Infinity === Infinity // TRUE
Infinity * 2 === Infinity * 5 // TRUE, so 2===5 if Infinity !== 0?
但是,这对我来说很有意义:
NaN * 2 === NaN * 5 // FALSE
问题
- JS为什么要这样设计?有什么特殊原因吗?
- 用 JS 编写数学表达式是否存在潜在威胁?
最佳答案
Why JS is designed so? Was there a particular reason for that?
JavaScript 直接从 IEEE-754 获取 NaN
(包括它永远不等于自身的事实)和无穷大。 ,计算中 float 的首选标准,许多其他语言也使用该标准。 (具体来说,它使用“quiet NaN ”。)反过来,IEEE-754 从数学理论中获得了很多信息(例如,Infinity + 1
=== Infinity
,显然这是 considered true for some kinds of numbers ,但我不是数学家;我认为标准的设计者有理由遵循该定义)。
Are there potentials threats when writing Maths expressions in JS?
我不会称它们为威胁,但是:NaN
将在出现的任何计算中传播。除此之外,您还遇到 this question and its answers 中讨论的常见精度问题。 .
关于JavaScript - Infinity 和 NaN 应该是数字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33722824/