Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get 0 by subtracting two unequal floating point numbers?

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.

like image 343
Thirler Avatar asked Oct 11 '22 01:10

Thirler


People also ask

Can you subtract floats?

To subtract two floating numbers in Python, use the subtract operator(-). Float is one of the most used numeric data types in Python.

Is 0.0 a floating point number?

'' If there is no minus zero, then 0.0 and -0.0 are both interpreted as simply a floating-point zero.

Can I subtract a integer from a float?

C++ Subtraction of Floating Point Number from IntegerYou can subtract an integer and floating point number using subtraction operator.


2 Answers

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.

like image 152
nwellnhof Avatar answered Oct 14 '22 01:10

nwellnhof


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.

like image 41
malarres Avatar answered Oct 14 '22 02:10

malarres