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

标签 ruby floating-point

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/

相关文章:

c++ - 为什么将 float64 转换为 int32 在 Go 中会给出负数?

java - 仅使用四种 HTTP 方法创建任何类型的 RESTful API?

ruby - 从 ruby​​ 中的 UUID v1 中提取时间

c++ - 使用 SSE 内在函数时如何确保 NaN 传播?

Python:解析由文本表示的长 double 组非常慢

javascript - 确定一个 float 是否是另一个 float 的倍数?

javascript - 在什么时候比较 "integer"和 "float"等于 `true` ?

ruby-on-rails - 无法使用Ckeditor、Paperclip和Ruby on Rails给图片模型添加参数

ruby - 我怎样才能完全重置我的 Ruby 安装?

ruby-on-rails - Ruby:编写嵌套 if 条件的更具可读性的方式?