Why in Ruby 0.0/0, 3.0/0 and 3/0 behave differently?

删除回忆录丶 提交于 2019-12-23 12:36:55

问题


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?


回答1:


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:

The standard defines arithmetic formats: sets of binary and decimal floating-point data, which consist of finite numbers (including signed zeros and subnormal numbers), infinities, and special "not a number" values (NaNs)

Whole numbers (0, 3) are treated as integers.

Both NaN and Infinity (as well as -Infinity) are special cases that such floats are designed to handle, but integers are not -- hence the error.




回答2:


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



来源:https://stackoverflow.com/questions/7726615/why-in-ruby-0-0-0-3-0-0-and-3-0-behave-differently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!