Integer
除以零引发 ZeroDivisionError
:
0 / 0 # ZeroDivisionError
但是
Float
除以零才不是: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
我想知道为什么
Integer
的行为会有这种差异和 Float
在 ruby ?
最佳答案
与几乎所有编程语言一样,ruby 的浮点运算实现符合 IEEE 754标准。
这个规范(上面链接)定义了五个异常(exception) 必须 (至少默认情况下)以特定方式处理:
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.
因此
1.0/0
必须等于 +Infinity
, 和 0.0/0
必须等于 NaN
.Integer
对象不符合上述标准。 (没有 Infinity
或 NaN
,并且所有操作都是精确的。)因此,为诸如 1/0
之类的操作引发异常是特定于语言的决定。 .
关于ruby - 为什么 Float 除以零不会在 Ruby 中引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60433495/