Why in Ruby 0.0/0, 3.0/0 and 3/0 behave differently?
If I divi开发者_如何转开发de 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?
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.
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
精彩评论