问题描述
在下面的例子中是否可以除以0(或无穷大)?
Is it possible to get division by 0 (or infinity) in the following example?
public double calculation(double a, double b)
{
if (a == b)
{
return 0;
}
else
{
return 2 / (a - b);
}
}
在正常情况下,当然不会。但是,如果 a
和 b
非常接近,可以(ab)
由于计算精度而导致为 0
In normal cases it will not, of course. But what if a
and b
are very close, can (a-b)
result in being 0
due to precision of the calculation?
请注意,此问题适用于Java,但是我认为这将适用于大多数编程语言。
Note that this question is for Java, but I think it will apply to most programming languages.
推荐答案
在Java中, a - b
从不等于
0
如果 a!= b
。这是因为Java要求支持非规范化数字的IEEE 754浮点运算。从适用于,减去不等数将永远不会产生零(不同于乘法),另请参见。
If an FPU works with denormalized numbers, subtracting unequal numbers can never produce zero (unlike multiplication), also see this question.
对于其他语言,这取决于。例如,在C或C ++中,IEEE 754支持是可选的。
For other languages, it depends. In C or C++, for example, IEEE 754 support is optional.
那就是说,表达式
2 /(a - b)
可能溢出,例如使用 a = 5e- 308
和 b = 4e-308
。
这篇关于通过减去两个不等的浮点数可以得到0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!