Comparing Floating Point Numbers


Float a = new Float(3.0f); Float b = new Float(3.0f); if (a.equals(b)) {   // they are equal }



Because of rounding errors that can occur when working with floating point numbers, you have to be a bit more careful when trying to compare them. Therefore, instead of comparing the basic Java floating point types of float and double using the == operator; you should instead compare their object equivalents. The equals() method on Float and Double will return true only if the two values are exactly the same, bit for bit, or if they are both the value NaN. The value NaN stands for not a number. This value indicates a value that is not a valid number.

In the real world, when comparing floating point numbers, you might not want to compare for an exact match, but within an acceptable difference range. This acceptable range is usually referred to as a tolerance. Unfortunately, there is no built-in capability to do this using the Java standard classes or types, but you could fairly easily create your own equals() method to achieve this. Here we show some code that you could use to create such a method:

float f1 = 2.99f; float f2 = 3.00f; float tolerance = 0.05f; if (f1 == f2) System.out.println("they are equal"); else {    if (Math.abs(f1-f2) < tolerance) {       System.out.println("within tolerance");    } }


We first compare the floating point numbers using the == operator. If they are identically equal, we print an appropriate message. If they are not equal, we check to see if the absolute value of their difference is less than the desired tolerance value. Using this technique, you could create a useful method that would take two floating point values and a tolerance, and return a result indicating whether the values are equal within the tolerance range.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net