Author | Topic: Comparing Double |
Mani ranch hand |
posted April 27, 2000 01:32 AM
The following code will print 1: Double a = new Double(Double.NaN); 2: Double b = new Double(Double.NaN); 3: 4: if( Double.NaN == Double.NaN ) 5: System.out.println("True"); 6: else 7: System.out.println("False"); 8: 9: if( a.equals(b) ) 10: System.out.println("True"); 11: else 12: System.out.println("False"); A) True True B) True False C) False True D) False False Ans given C??
|
Brian, Nice greenhorn |
posted April 27, 2000 05:47 AM
From JavaDoc: Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if d1.doubleValue() == d2.doubleValue() If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN==Double.NaN has the value false. If d1 represents +0.0 while d2 represents -0.0, or vice versa, the equal test has the value false, even though +0.0==-0.0 has the value true. This allows hashtables to operate properly. HTH!
|
Suma Narayan ranch hand |
posted April 27, 2000 06:21 AM
Double a = new Double(Double.NaN) Double b = new Double(Double.NaN) A) True
Explanation given in JLS. Except for NaN, floating-point values are ordered; arranged from smallest to largest, they are negative infinity, negative finite nonzero values, negative zero, positive zero, positive finite nonzero values, and positive infinity. NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN . The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN . In particular, x!=x is true if and only if x is NaN, and (x Consider the following e.g public class AverageFruit if(average1==average2) The second calculation with a and b is of type 0/0. This gives indeterminate result. Both will have value NaN. But the result of a==b will result in false. To summarize: For any value of x, including NaN itself, all of the following comparisons will return false. x < Double.NaN NOTE: Double.NaN != Double.NaN will return TRUE. I hope the above explanation will help you.
|
Suma Narayan ranch hand |
posted April 27, 2000 06:38 AM
Hi Mani, After I submitted my reply to your question, I realized that I have missed the main point (Why a==b is false and why not a.equals(b)???) and instead explained all general things which I am sure you already know them. Before I could give an appropriate answer, Brian had already answered. Thanks Brian.
|
maha anna bartender |
posted April 27, 2000 08:06 AM
If you have a float and if you want to check it is NaN (Not a Number), you have to use either Float.isNaN(Float f) or Double.isNaN(Double d) . This will give true if the arg is NaN. The == comparision will give always false if one of the operands is NaN. regds maha anna
|
Mani ranch hand |
posted April 27, 2000 08:43 AM
Thanks to all..
|
| | |