Ensuring the Accuracy of Floating-Point Numbers

Problem

You want to know if a floating-point computation generated a sensible result.

Solution

Compare with the INFINITY constants, and use isNaN( ) to check for “not a number.”

Fixed-point operations that can do things like divide by zero will result in Java notifying you abruptly by throwing an exception. This is because integer division by zero is considered a logic error.

Floating-point operations, however, do not throw an exception, because they are defined over an (almost) infinite range of values. Instead, they signal errors by producing the constant POSITIVE_INFINITY if you divide a positive floating-point number by zero, the constant NEGATIVE_INFINITY if you divide a negative floating-point value by zero, and NaN, (Not a Number) if you otherwise generate an invalid result. Values for these three public constants are defined in both the Float and the Double wrapper classes. The value NaN has the unusual property that it is not equal to itself, that is, NaN != NaN. Thus, it would hardly make sense to compare a (possibly suspect) number against NaN, because the expression:

x == NaN

can therefore never be true. Instead, the methods Float.isNaN(float) and Double.isNaN(double) must be used:

// InfNan.java public static void main(String argv[]) { double d = 123; double e = 0; if (d/e == Double.POSITIVE_INFINITY) System.out.println("Check for POSITIVE_INFINITY works"); double s = Math.sqrt(-1); if (s == Double.NaN) System.out.println("Comparison ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.