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

If I divide by 0, I get either ZeroDivisionError, Infinity, or NaN depending on what is split.

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 infinity (in mathematical terms), but 3.0 / 0 is why then there is no 3/0 infinity? Why is integer division throwing an exception, but no float splitting?

+4
source share
2 answers

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: binary and decimal floating-point data sets consisting of finite numbers (including signed zeros and subnormal numbers), infinity, and special non-number values ​​( NaNs )

Integers ( 0 , 3 ) are treated as integers.

Both NaN and Infinity (as well as -Infinity ) are special cases when such floats are intended to be processed, but integers are not, therefore, an error.

+9
source

The reason that 3.0 / 0 is equal to Infinity is the IEEE 754 specification (the 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 quite interesting: http://users.tkk.fi/jhi/infnan.html

+3
source

All Articles