• Post Reply Bookmark Topic Watch Topic
  • New Topic

NaN Loop  RSS feed

 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please run the following code and let me know what happens. I have run it using jdk1.5.0_04 and I do not get the result I expect - contrary to JLS 3rd Edition


Thanks
-Barry
[ July 28, 2005: Message edited by: Barry Gaunt ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My laptop doesn't have 1.5 installed on it, so I'm going to guess: the double NaN is getting autoboxed into a Double; comparing two Doubles with == or != doesn't care about the values, just the object identity, just like any other class -- so it doesn't loop. Am I right?
 
James Sabre
Ranch Hand
Posts: 781
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even if you change

Double i = Double.NaN;

to

double i = Double.NaN;

you will still have a problem because using == on NaN compares false against anything, even itself.

To test a double for NaN you need to use Double.isNaN(value).
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JLS says that Double.NaN != Double.NaN must return true, and NaN is the only value that does this, but it is returning false. This is an example from "Java Puzzlers" by Bloch & Gafter.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You got it Ernest and James.

Ok, I see my MFU. I should be saying double i = Double.NaN;

Slip of the fist on the keyboard is my excuse...

Thanks for your replies.
-Barry

[ July 28, 2005: Message edited by: Barry Gaunt ]
[ July 28, 2005: Message edited by: Barry Gaunt ]
 
James Sabre
Ranch Hand
Posts: 781
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Double.NaN is a double but your 'i' is a Double. Therefore i == i is true and i != i is false.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!