Wild Goat
Wild Goat

Reputation: 3579

Primitive double equals to NaN

Can someone explain how does it possible that primitive double type equals to NaN after following computations. Can you tell me some cases when double could end up as Nan? Thanks!

double averagePrecisionExisting = 0;
for (int i = 0; i < x; i++)
    averagePrecisionExisting += logicWhichReturnsPrimitiveDouble();

double meanAveragePrecisionExisting = averagePrecisionExisting / x.size();    
System.out.println("Mean average precision of existing algorithm  = " + meanAveragePrecisionExisting);

Output: Mean average precision of existing algorithm = NaN

Upvotes: 0

Views: 674

Answers (3)

bastijn
bastijn

Reputation: 5953

Well, NaN is produced if a floating point operation has some input parameters that cause the operation to produce some undefined result (e.g. 0.0 / 0.0).

It seems that if your x is zero and x.size() returns zero you will do exactly that.

Upvotes: 1

assylias
assylias

Reputation: 328608

For example, these are NaNs:

  • 0d /0d
  • Double.POSITIVE_INFINITY / Double.POSITIVE_INFINITY
  • Double.POSITIVE_INFINITY / Double.NEGATIVE_INFINITY
  • Double.NaN + 1

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500535

Assuming your loop is meant to use x.size(), then it's pretty simple - if x.size() is 0, you'll be computing 0/0, which is NaN.

Otherwise, it could be that logicWhichReturnsPrimitiveDouble() returns a NaN for whatever reason. It's not clear why you've emphasized the "primitive" part in various places in your post - a primitive double is just as capable of representing NaN as Double. Indeed, the type of Double.NaN is double...

Upvotes: 8

Related Questions