This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Output of this code

 
Swati Kadam
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println(Double.NaN == Double.NaN );
It prints False...
Why is it so?
 
Sandip Kaviman
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because NaN is not equal anything even to itself also(as per K&B).

but still this does not answer why it is not equal to itself

 
Irina Goble
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sandip K:
Because NaN is not equal anything even to itself also(as per K&B).

but still this does not answer why it is not equal to itself



It is not equal to itselt, so you can find out that it is a NaN:
 
Mike Simmons
Ranch Hand
Posts: 3040
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also use Double.isNaN() to find out if a double is a NaN. Similarly Float.isNaN() for floats. That might be slightly clearer to programmers who forget about the existence of NaN.

Swati, Sandip - the reason NaN != NaN is by design. What should happen here?

Here two different calculations have the result NaN - should they be equal to each other? Probably not. They're both NaN, but they're different. Even if both x and y were 1.0/ 0.0, the word "equals" doesn't really have any clear meaning when you're talking about a number that is not a number. Equal to what? It's a special case, and Java has special rules for it. So do several other languages, since the idea of NaN existed before Java.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic