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);
}
}
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?
Note that this question is for Java, but I think it will apply to most programming languages.
To subtract two floating numbers in Python, use the subtract operator(-). Float is one of the most used numeric data types in Python.
'' If there is no minus zero, then 0.0 and -0.0 are both interpreted as simply a floating-point zero.
C++ Subtraction of Floating Point Number from IntegerYou can subtract an integer and floating point number using subtraction operator.
In Java, a - b
is never equal to 0
if a != b
. This is because Java mandates IEEE 754 floating point operations which support denormalized numbers. From the spec:
In particular, the Java programming language requires support of IEEE 754 denormalized floating-point numbers and gradual underflow, which make it easier to prove desirable properties of particular numerical algorithms. Floating-point operations do not "flush to zero" if the calculated result is a denormalized number.
If an FPU works with denormalized numbers, subtracting unequal numbers can never produce zero (unlike multiplication), also see this question.
For other languages, it depends. In C or C++, for example, IEEE 754 support is optional.
That said, it is possible for the expression 2 / (a - b)
to overflow, for example with a = 5e-308
and b = 4e-308
.
As a workaround, what about the following?
public double calculation(double a, double b) {
double c = a - b;
if (c == 0)
{
return 0;
}
else
{
return 2 / c;
}
}
That way you don't depend on IEEE support in any language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With