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?
The IEEE floating-point standard, supported by almost all modern floating-point units, specifies that every floating-point arithmetic operation, including division by zero, has a well-defined result. The standard supports signed zero, as well as infinity and NaN (not a number).
Floating point error means that there is a division by a zero value in your code. It can be a variable, input, or a function in use that returns zero value. You need to identify this variable/input/function and make sure that the returned value is not zero.
Dividing a floating-point value by zero doesn't throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic.
Trying to divide an integer or Decimal number by zero throws a DivideByZeroException exception. To prevent the exception, ensure that the denominator in a division operation with integer or Decimal values is non-zero.
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
.
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