Java Reference
In-Depth Information
Using == to compare 0 and -0
numbers are equal
Using equals() to compare 0 and -0
numbers are not equal
Using equals() to compare two NaNs
NaNs are equal
On the Web
The program FpComp.java is located in the Chapter 24 folder at
www.crcpress.com .
Weighted comparisons
Java comparisons in regards to valid numeric values (not NaNs or infini-
ties) of primitive floating point types, or of floating-point objects of the
classes Double and Float, return true if both values are bit-by-bit identical.
This is often undesirable in engineering or scientific applications in which
different routes used in calculations can lead to small differences. In other
words, the code needs to determine not if two values are identically equal,
but if they are approximately equal to some pre-determined degree.
The Greek letter epsilon is sometimes used in mathematics to define a
small quantity. In this sense we can describe the weighted equality of two
operands if their values are within some tolerance, represented as epsi-
lon. If the value of epsilon is defined as a constant we can develop an
overloaded version of the equals() method to test for weighted equality.
For example:
final static double EPSILON = 1.0E-12;
// Method overloading equals()
public static boolean equals(double v1, double v2, double e)
{
return Math.abs(v1 - v2) < e;
}
In this case the method calculates the absolute difference between the
two operands and returns true if this differences is smaller than the value
defined for the constant passed as the third argument. The following pro-
gram demonstrates the difference between absolute and weighted equal-
ity.
// Java for Engineers
// Filename: WtComp
// Reference: Chapter 24
// Description:
//
Weighted floating-pioint comparisons
Search WWH ::




Custom Search