Wednesday, 20 April 2011

Floating Point and Divide By Zero

Did you know that dividing a double by zero will not throw an ArithmeticException? This seems rather inconsistent to me as dividing an int by zero will.

    double x;
    x =
24.0 / 0;


The code above simply prints the word "Infinity", whilst the code below throws the exception...

    int y;
    y =
24 / 0;


Why this is, I guess, is down to the definition of a double. Note that x is a number and hence:

    if (Double.isNaN(x)) {
System.out.println("x is not a number");

will not print anything. To detect a divide by zero using floating point arithmetic, you need to check for infinity:

    if (Double.isInfinite(x)) {
System.out.println("x is infinite");

No comments: