Scala: why 1/0 is an arithmetic exception, but 1.0 / 0.0 = Double.Infinity

It seems inconsistent that in Scala, the integer arithmetic div throws a java.lang.ArithmeticException: / by zero , but the floating point arithmetic ( 1.0/0.0 ) returns Double.Infinity .

I understand that in terms of type it may seem difficult to have both Double.Infinity and Integer.Infinity, but I assume that with a powerful scala type system they could figure out some other way to solve this aspect of the problem.

Is there anything else that I am missing that it is better to explain these two different behaviors?

+6
source share
1 answer

This is a hardware limitation, not software, and the reason is simple: IEEE754 floating point arithmetic explicitly supports +Inf and -Inf , i.e. there are bit representations corresponding to these two ideas, and therefore, it makes sense for them to be the result of 1.0/0.0 .

Integer arithmetic implemented in conventional processors has no internal representation for infinity and therefore should cause an error.

You can implement an integral type that supports infinities in software, but it will be slower since the division operation will not correspond directly to the div processor. In my opinion, this is unreasonable: Integer div-by-zero errors are almost always associated with (a) incorrect implementation of your algorithm or (b) incorrect validation of user input, which are fundamental problems that must be solved before compiling your code, and not at runtime through exceptions! On the other hand, in FP arithmetic you can easily run div-by-zero when you don't (and really can't): 1e-308/1e+308 has the correct value, but it cannot be represented as double even though both operands.

+15
source

All Articles