Java – Scala divided by zero produces different results

I'm confused about how Scala handles division by zero This 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 example above, depending on how you divide by zero, you will get one of the following:

>“java.lang.ArithmeticException:/ by zero” >“Double = NaN” >“Double = Infinity”

This makes debugging very challenging, especially when dealing with data with unknown characteristics What is the reason behind this approach, and even better, how to deal with division by zero in a unified way in scala?

Solution

All types of zero rules boil down to division

0 / 0 is an integer divided by zero (because both parameters are integer literals), which is a Java Required for lang.arithmeticexception

1.toDouble / 0. ToDouble is a floating-point division by zero with positive numerator, which needs to be evaluated to infinity

0.0 / 0.0 is floating-point division by zero, zero numerator, and needs to be evaluated as Nan

The first is the Java and scala conventions, and the other two are IEEE754 floating point attributes, which are used by both Java and scala

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>