为什么在 Ruby 0.0/0、3.0/0 和 3/0 中表现不同?
如果我除以 0,我会得到 ZeroDivisionError、Infinity 或 NaN,具体取决于除什么。
ruby-1.9.2-p180 :018 > 0.0 / 0
=> NaN
ruby-1.9.2-p180 :020 > 3.0 / 0
=> Infinity
ruby-1.9.2-p180 :021 > 3 / 0
ZeroDivisionError: divided by 0
我知道 0.0 / 0 不是无穷大(用数学术语来说),而 3.0 / 0 是无穷大,但为什么 3 / 0 不是无穷大呢?为什么除整数会引发异常,而除浮点数却不会?
If I divide by 0, I get either a ZeroDivisionError, Infinity or NaN depending on what is divided.
ruby-1.9.2-p180 :018 > 0.0 / 0
=> NaN
ruby-1.9.2-p180 :020 > 3.0 / 0
=> Infinity
ruby-1.9.2-p180 :021 > 3 / 0
ZeroDivisionError: divided by 0
I understand that 0.0 / 0 is not an Infinity (in math terms), while 3.0 / 0 is but why then isn't 3 / 0 an Infinity? Why dividing an integer throws an exception but dividing a float doesn't?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Ruby 中,并非所有数字都是平等的(双关语)。
十进制数字(
0.0
、3.0
)遵循 IEEE 754 -2008浮点运算标准:整数(
0
、3
)被视为整数。NaN
和Infinity
(以及-Infinity
)都是此类浮点数旨在处理的特殊情况,但整数不是 - 因此错误。In Ruby, not all numbers are created equal (pun intended).
Decimal numbers (
0.0
,3.0
) follow the IEEE 754-2008 standard for floating point arithmetic:Whole numbers (
0
,3
) are treated as integers.Both
NaN
andInfinity
(as well as-Infinity
) are special cases that such floats are designed to handle, but integers are not -- hence the error.3.0/0 等于 Infinity 的原因是 Ruby 实现的 IEEE 754 规范(浮点算术标准)。
http://weblog.jamisbuck.org/2007/2/7/infinity
http://en.wikipedia.org/wiki/IEEE_754
顺便说一句,我发现这个表非常有趣: http://users.tkk.fi/jhi/infnan.html< /a>
The reason why 3.0/0 equals Infinity is the IEEE 754 specification (Standard for Floating-Point Arithmetic), which Ruby implements.
http://weblog.jamisbuck.org/2007/2/7/infinity
http://en.wikipedia.org/wiki/IEEE_754
Btw, I find this table pretty interesting: http://users.tkk.fi/jhi/infnan.html