1

Can anyone explain why the flag value is returning False?

double a = 1.0;
double b = 0.0;
double c = a / b;
boolean flag = Double.isNaN(c);
System.out.println(flag); // False?
System.out.println(c); // Infinity
Grs007
  • 129
  • 1
  • 1
  • 7

2 Answers2

2

This is due to the definition of floating-point representation in the IEEE 754 standard. The standard has representations for both "infinity" and "NaN". "Infinity" is for operations that either produce an infinite result (such as 1/0 or tan(pi/2) [*]) or produce a result whose absolute value is larger than the largest possible number the format can represent. More precisely, in math, there really isn't such a thing as an infinite result; rather, it's defined in terms of limits. Thus, 1/0 doesn't exist, but the limit of 1/x as x approaches 0 is infinite.

NaN is returned for "indeterminate forms". In math, these are cases such as 0/0 when the limit can't be determined just by looking at the numerator and denominator. (If you have two functions f(x) and g(x) where the values are both 0 at some point f(a)=g(a)=0, then you can't determine the limit of f(x)/g(x) as x approaches a, without extra work such as L'Hopital's rule.) NaN is also returned for things like taking the square root of a negative number.

In Java, isNan returns true only for actual NaN's, not for infinities. Even though infinity really is "not a number", it doesn't meet the definition of a NaN according to the IEEE standard.

See here for a definition of which operations generate NaN.

[*] Note that "pi" can't be represented exactly in a floating-point number, so this really isn't an operation that could produce an "infinite result" on a computer.

ajb
  • 31,309
  • 3
  • 58
  • 84
1

That's what the IEEE-754 standard says. When you divide a non-zero floating point number by zero, it does not return a number, but infinity.

Take a look at this: http://grouper.ieee.org/groups/754/faq.html#exceptions

Tavo
  • 3,087
  • 5
  • 29
  • 44
  • "When you divide a floating point number by zero" should be "When you divide a non-zero floating point number by zero". 0/0 will return a NaN. – ajb Jul 05 '17 at 05:49
  • You are absolutely right. Edited. Thanks! :) – Tavo Jul 05 '17 at 06:03