scala:为什么1/0是算术异常,但1.0 / 0.0 = Double.Infinity [英] scala: why is 1/0 an arithmetic exception but 1.0/0.0 = Double.Infinity

查看:397
本文介绍了scala:为什么1/0是算术异常,但1.0 / 0.0 = Double.Infinity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎不一致的是,在Scala中,整数算术div除零会抛出 java.lang.ArithmeticException:/ by zero ,但是浮点运算( 1.0 / 0.0 )返回 Double.Infinity

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

我从中了解到类型透视,同时拥有Double.Infinity和Integer.Infinity可能会很棘手,但我认为使用scala强大的类型系统,他们可能已经找到了解决问题方面的其他方法。

I understand that from a type perspective it might be tricky to have both a Double.Infinity and an Integer.Infinity, but I assume with scala's powerful type system they could have figured out some other way to resolve that aspect of the problem.

我还缺少哪些可以更好地解释这两种不同的行为?

Is there something else I'm missing that would better explain these two differing behaviors?

推荐答案

这是硬件限制,而不是软件限制,原因很简单:IEEE754浮点运算明确支持 + Inf -Inf ,即有一些位表示与这两个想法相对应,因此它们是 1.0 / 0.0 的结果。

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

In在普通处理器中实现的teger算法没有无穷大的内部表示,因此必须抛出错误。

Integer arithmetic as implemented in common processors does not have an internal representation for infinities, and therefore has to throw an error.

你可以实现一个支持软件无穷大的整数类型但是它会慢一些,因为除法运算不会直接对应处理器
div 指令。在我看来,这是不明智的:由于(a)算法的错误实现或(b)无法正确验证用户输入,因此整数div-by-zero错误几乎总是,这两者都是在编译代码之前必须解决的基本问题,而不是在运行时通过异常!另一方面,在FP算术中,当你没有(并且实际上不能)期望它时,你可能很容易遇到div:0:$ code> 1e-308 / 1e + 308 具有正确的值,但它不能表示为 double ,即使两个操作数都是。

You could implement an integral type that supports infinities in software, but it would be slower as a division operation would not correspond directly to the processor 's div instruction. This is not sensible in my opinion: Integer div-by-zero errors are almost always due to (a) incorrect implementation of your algorithm or (b) failure to validate user input correctly, both of which are fundamental problems that have to be tackled before you compile your code, not at runtime via exceptions! In FP arithmetic on the other hand, you may easily run into div-by-zero when you don't (and really cannot) expect it: 1e-308/1e+308 has a correct value, but it is not representable as a double even though both operands are.

这篇关于scala:为什么1/0是算术异常,但1.0 / 0.0 = Double.Infinity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆