Understanding NaN

Arjun Reddy
Ranch Hand
Posts: 629
Hi All,

What does Float.NaN mean in Float f1 = new Float(Float.NaN)? and also, in the below code, why is -0.0f == 0.0f true?

Thanks.

Henry Wong
author
Marshal
Posts: 21024
78
The reason 0.0f == -0.0f is because IEEE defines it as so. The reason the float class doesn't adhere to IEEE is because it wants 0.0f and -0.0f to be used as keys in a hashmap/set. (The JavaDoc clearly states this deviation from the IEEE specification)

Henry
[ September 07, 2008: Message edited by: Henry Wong ]

Henry Wong
author
Marshal
Posts: 21024
78
NaN means "not a number". It is a valid value defined by the IEEE specification. And can be achieve with certain calculations. For example, the square root of a negative number is a NaN. Zero divided by zero results in NaN.

And Float.NaN is simply a static variable of the Float class that holds this value. This is so that you can compare results to see if it is NaN, without having to calculate it yourself.

Henry
[ September 07, 2008: Message edited by: Henry Wong ]

Arjun Reddy
Ranch Hand
Posts: 629
So, -1.2f == 1.2f is only for floats and doubles right and also, say, Float.NaN == Float.NaN is false because we can not compare two values which are undefined or unknown maybe right?

Thanks.

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15219
36
No, -1.2f == 1.2f is ofcourse false. Those are two different values.

There is only one value for zero. There are (mathematically) not two numbers "negative zero" and "positive zero".

NaN == NaN is false, because it is defined that way.

Lok Manick
Ranch Hand
Posts: 73
NaN can be related to infinity in maths ( i cannot find the symbol in my keyboard )

infinity is always != infinity

|||ly NaN != NaN

Arjun Reddy
Ranch Hand
Posts: 629
Thanks for the replies guys.

Bert Bates
author
Sheriff
Posts: 8898
5
Hi Guys,

This discussion applies only to the 1.4 exam - when the Math class got removed from the objectives so did NaN.

hth,

Bert

Arjun Reddy
Ranch Hand
Posts: 629
Thanks for letting us know. I am actually preparing on SCJP 1.5 exam

Ankit Garg
Sheriff
Posts: 9519
22
Whooa!!! I didn't knew that Math class is not in the objectives. I was wondering why the book doesn't cover Math class.....