除以零产生不同的结果

除以零产生不同的结果

本文介绍了Scala 除以零产生不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Scala 如何处理除以零感到困惑.这是一个 REPL 代码片段.

I am confused with how Scala handles division by zero. Here is a REPL code snippet.

scala> 1/0
java.lang.ArithmeticException: / by zero
  ... 33 elided

scala> 1.toDouble/0.toDouble
res1: Double = Infinity

scala> 0.0/0.0
res2: Double = NaN

scala> 0/0
java.lang.ArithmeticException: / by zero
  ... 33 elided

scala> 1.toInt/0.toInt
java.lang.ArithmeticException: / by zero
  ... 33 elided

如上例所示,根据您除以零的方式,您会得到以下结果之一:

As you can see in the above example, depending on how you divide by zero, you get one of the following:

  • "java.lang.ArithmeticException:/by zero"
  • "Double = NaN"
  • 双 = 无穷大"

这使得调试非常具有挑战性,尤其是在处理未知特征的数据时.这种方法背后的原因是什么,或者甚至更好的问题,如何在 Scala 中以统一的方式处理除以零?

This makes debugging quite challenging especially when dealing with data of unknown characteristics. What is the reasoning behind this approach, or even a better question, how to handle division by zero in a unified manner in Scala?

推荐答案

归根结底是各种类型的除零规则.

It's all down to the division by zero rules for various types.

0/0被零整除(因为两个参数都是整数文字),并且需要抛出 java.lang.ArithmeticException.

0 / 0 is an integer division by zero (as both arguments are integer literals), and that is required to throw a java.lang.ArithmeticException.

1.toDouble/0.toDouble 是一个带有正分子的浮点数除以零,需要计算为 +Infinity.

1.toDouble/0.toDouble is a floating point division by zero with a positive numerator, and that is required to evaluate to +Infinity.

0.0/0.0 是用零分子除以零的浮点数,需要计算为 +NaN.

0.0/0.0 is a floating point division by zero with a zero numerator, and that is required to evaluate to +NaN.

第一个是 Java 和 Scala 约定,另外两个是 IEEE754 浮点的属性,这是 Java 和 Scala 都使用的.

The first is a Java and Scala convention, the other two are properties of IEEE754 floating point, which is what Java and Scala both use.

这篇关于Scala 除以零产生不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 19:16