Java Reference
In-Depth Information
if(res == Double.NEGATIVE_INFINITY)
System.out.println(“result is NEGATIVE_INFINITY”);
if(res == Double.POSITIVE_INFINITY)
System.out.println(“result is POSITIVE_INFINITY”);
// Test for either infinity
if(Double.isInfinite(res))
System.out.println(“result is infinite”);
// Get user input for square root
System.out.println(“\nCalculating square root (try negative)”);
root = Keyin.inDouble(“Enter root: ”);
res = Math.sqrt(root);
if(Double.isNaN(res))
System.out.println(“result is Nan”);
else
System.out.println(“Square root=”+res);
}
}
On the Web
The program FpError.java is found in the Chapter 24 folder at
www.crcpress.com .
Comparing Floating-Point Numbers
The comparison operator (==) can be used for comparing double or float
valueswith finite operands, but the results are not always as expected. Con-
sider the following code fragment:
double num1 = -0.0;
double num2 = 0.0;
if(num1 == num2)
System.out.println(“numbers are equal”);
else
System.out.println(“numbers not equal”);
The result of this test is that negative zero and positive zero are re-
ported as equal values. In the preceding section you saw that compari-
sons may also fail when one or both operands are NaNs. The class
java.lang.Object provides a method named equals() that allows compar-
ing two objects. This method is overridden in the subclasses of Object,
such as Byte, Short, Integer, Long, Double, Float, BigDecimal, and
BigInteger. Therefore, the equals() method can be used to compare nu-
meric values of any type. The equals() method is defined in the
java.lang.Object as follows:
public boolean equals(Object obj)
Search WWH ::




Custom Search