Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can Java produce a NaN?

Tags:

java

nan

I know what Java Double.NaN is. I have some Java code that produces NaN.

// calculate errors
delta = m1 + m2 - M;
eta = f1 + f2 - F;
for (int i = 0; i < numChildren; i++) {
  epsilon[i] = p[i]*m1+(1-p[i])*m2+q[i]*f1+(1-q[i])*f2-C[i];
}

// use errors in gradient descent
// set aside differences for the p's and q's
float mDiff = m1 - m2;
float fDiff = f1 - f2;
// first update m's and f's
m1 -= rate*delta;
m2 -= rate*delta;
f1 -= rate*eta;
f2 -= rate*eta;
for (int i = 0; i < numChildren; i++) {
  m1 -= rate*epsilon[i]*p[i];
  m2 -= rate*epsilon[i]*(1-p[i]);
  f1 -= rate*epsilon[i]*q[i];
  f2 -= rate*epsilon[i]*(1-q[i]);
}
// now update the p's and q's
for (int i = 0; i < numChildren; i++) {
  p[i] -= rate*epsilon[i]*mDiff;
  q[i] -= rate*epsilon[i]*fDiff;  
}

Under what circumstances will Java produce a NaN value?

like image 408
Brent Avatar asked May 22 '10 06:05

Brent


1 Answers

NaN is triggered by the following occurrences:

  • results that are complex values
    • √x where x is negative
    • log(x) where x is negative
    • tan(x) where x mod 180 is 90
    • asin(x) or acos(x) where x is outside [-1..1]
  • 0/0
  • ∞/∞
  • ∞/−∞
  • −∞/∞
  • −∞/−∞
  • 0×∞
  • 0×−∞
  • 1
  • ∞ + (−∞)
  • (−∞) + ∞

Sorry for such a general answer, but I hope that helped.

like image 184
Delan Azabani Avatar answered Sep 24 '22 23:09

Delan Azabani