Reputation: 1131
Dividing by zero for Integer
raises a ZeroDivisionError
:
0 / 0 # ZeroDivisionError
However dividing by zero for Float
does not:
0.0 / 0 #NaN
0 / 0.0 #NaN
0.0 /0.0 #NaN
1.0 / 0 #Infinity
1 / 0.0 #Infinity
1.0 /0.0 #Infinity
I was wondering why is there this difference in behaviour for Integer
and Float
in Ruby?
Upvotes: 6
Views: 739
Reputation: 28305
As with almost all programming languages, ruby's implementation of floating-point arithmetic is compliant to the IEEE 754 standard.
This specification (linked above) defines five exceptions that must (at least by default) be handled in a specific way:
Invalid operation: mathematically undefined, e.g., the square root of a negative number. By default, returns qNaN.
Division by zero: an operation on finite operands gives an exact infinite result, e.g., 1/0 or log(0). By default, returns ±infinity.
Overflow: a result is too large to be represented correctly (i.e., its exponent with an unbounded exponent range would be larger than emax). By default, returns ±infinity for the round-to-nearest modes (and follows the rounding rules for the directed rounding modes).
Underflow: a result is very small (outside the normal range) and is inexact. By default, returns a subnormal or zero (following the rounding rules).
Inexact: the exact (i.e., unrounded) result is not representable exactly. By default, returns the correctly rounded result.
Therefore 1.0/0
must equal +Infinity
, and 0.0/0
must equal NaN
.
Integer
objects do not conform to the above standard. (There is no Infinity
or NaN
, and all operations are exact.) Therefore, it was a language-specific decision to raise an exception for operations such as 1/0
.
Upvotes: 10