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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With