JavaScript - Infinity 和 NaN 应该是数字吗?
JavaScript - should Infinity and NaN be numbers?
少量实验
我打算用 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, the go-to standard for floating point numbers in computing, which is also used by many other languages. (Specifically, it uses a "quiet NaN".) IEEE-754, in turn, gets a lot of this from mathematic theory (e.g., Infinity + 1
=== Infinity
, apparently this is considered true for some kinds of numbers 获取 NaN
(包括它永远不等于自身的事实)和无穷大,但我不是数学家;我假设标准的设计者有遵循该定义的理由)。
Are there potentials threats when writing Maths expressions in JS?
我不会称它们为威胁,但是:NaN
会在它出现的任何计算中传播。除此之外,您还有 this question and its answers.
中讨论的常见精度问题
这里有一个关于两个 NaN 不等式的答案 - Why is NaN === NaN false?。至于无穷大,这是一个纯数学——无穷大乘以任何东西都是无穷大。最后, typeof returns "number" 用于 Infinity 和 NaN 只是因为它们是 JS 中数字类型的常量。
少量实验
我打算用 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, the go-to standard for floating point numbers in computing, which is also used by many other languages. (Specifically, it uses a "quiet NaN".) IEEE-754, in turn, gets a lot of this from mathematic theory (e.g., Infinity + 1
=== Infinity
, apparently this is considered true for some kinds of numbers 获取 NaN
(包括它永远不等于自身的事实)和无穷大,但我不是数学家;我假设标准的设计者有遵循该定义的理由)。
Are there potentials threats when writing Maths expressions in JS?
我不会称它们为威胁,但是:NaN
会在它出现的任何计算中传播。除此之外,您还有 this question and its answers.
这里有一个关于两个 NaN 不等式的答案 - Why is NaN === NaN false?。至于无穷大,这是一个纯数学——无穷大乘以任何东西都是无穷大。最后, typeof returns "number" 用于 Infinity 和 NaN 只是因为它们是 JS 中数字类型的常量。