Java Reference
In-Depth Information
Floating-point errors
Floating-point numbers are defined over an almost unlimited range. There-
fore floating-point operations do not throwarithmetic exceptions. Instead,
they signal errors by producing error constants. For example, if you divide
by an integer value of zero the program stops abruptly, generating the mes-
sage:
ArithmeticException: /by zero at ...
On the other hand, if you divide a floating-point number by zero the re-
sult is the constant POSITIVE_INFINITY if the dividend is a positive num-
ber, or the constant NEGATIVE_INFINITY if the dividend is a negative
number. If the result is otherwise invalid a floating-point operation pro-
duces NaN (Not a Number).
The constants NaN, POSITIVE_INFINITY, and NEGATIVE_INFINITY
are defined in the wrapper classes Double and Float of the java.lang pack-
age. In addition, these classes provide methods that test whether a value
is a NaN or an Infinity. Providing a method to test for a NaN is necessary
because NaNs have the property of not being equal to themselves. The ex-
pression
if(val == Double.NaN)
will never evaluate to true. The following program demonstrates error de-
tection of floating-point results.
// Java for Engineers
// Filename: FpError
// Reference: Chapter 24
// Description:
//
Floating-pioint error diagnostics
// Requires:
//
Keyin class in current directory
import java.lang.*;
class FpError
{
public static void main(String[] args)
{
double res;
double divisor = 0;
double dividend, root;
// Get user input for numerator
System.out.println(“Forcing division by zero error”);
dividend = Keyin.inDouble(“Enter dividend: ”);
res = dividend/divisor;
// Test for negative invifinity
Search WWH ::




Custom Search