gpt4 book ai didi

ruby - 为什么 Float 除以零不会在 Ruby 中引发异常?

转载 作者:行者123 更新时间:2023-12-03 15:48:37 25 4
gpt4 key购买 nike

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对象不符合上述标准。 (没有 InfinityNaN ,并且所有操作都是精确的。)因此,为诸如 1/0 之类的操作引发异常是特定于语言的决定。 .

关于ruby - 为什么 Float 除以零不会在 Ruby 中引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60433495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com