Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Integer represent NaN in Java?

When I write something like

double a = 0.0;
double b = 0.0;
double c = a/b;

The result is Double.NaN, but when I try the same for integers, it produces an ArithmeticException. So, why isn't there a Integer.NaN?

like image 296
JavaNewbie_M107 Avatar asked Jul 12 '13 13:07

JavaNewbie_M107


2 Answers

The answer has very little to do with Java. Infinity or undefined numbers are not a part of the integer set, so they are excluded from Integer, whereas floating point types represent real numbers as well as complex numbers, so to deal with these, NaN has been included with floating point types.

like image 106
Trilokeshwar Shonku Avatar answered Oct 13 '22 10:10

Trilokeshwar Shonku


For the same reason that there is no integer NaN in any other language.

Modern computers use 2's complement binary representation for integers, and that representation doesn't have a NaN value. (All values in the domain of the representation type represent definite integers.)

It follows that computer integer arithmetic hardware does not recognize any NaN representation.

In theory, someone could invent an alternative representation for integers that includes NaN (or INF, or some other exotic value). However, arithmetic using such a representation would not be supported by the hardware. While it would be possible to implement it in software, it would be prohibitively expensive1... and undesirable in other respects too to include this support in the Java language.

1 - It is of course relative, but I'd anticipate that a software implementation of NaNs would be (at least) an order of magnitude slower than hardware. If you actually, really, needed this, then that would be acceptable. But the vast majority of integer arithmetic codes don't need this. In most cases throwing an exception for "divide by zero" is just fine, and an order of magnitude slow down in all integer arithmetic operations is ... not acceptable.


By contrast:

  • the "unused" values in the representation space already exist
  • NaN and INF values are part of the IEE floating point standard, and
  • they are (typically) implemented by the native hardware implementation of floating point arithmetic
like image 31
Stephen C Avatar answered Oct 13 '22 10:10

Stephen C