Why does Integer not 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 to do the same for integers, it throws an ArithmeticException . So why not Integer.NaN ?

+6
source share
3 answers

The answer is very little related to Java. Infinity or undefined numbers are not part of the integer set, so they are excluded from Integer , while floating-point types represent real numbers as well as complex numbers, so floating-point types were included to solve these problems.

+8
source

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

Modern computers use a binary representation with two additions for integers, and this representation does not matter NaN. (All values ​​in the scope of the view type represent specific integers.)

It follows that the computer integer arithmetic equipment does not recognize any representation of NaN.

In theory, someone could invent an alternative representation for integers that includes NaN (or INF, or some other exotic meaning). However, arithmetic using this representation will not be supported by hardware. Although it would be possible to implement it in software, it would be overly expensive 1 ... and undesirable in other respects to also include this support in the Java language.

1 - This, of course, is relative, but I would expect that the software implementation of NaNs would be (at least) an order of magnitude slower than the hardware. If you really, really needed it, then that would be acceptable. But the vast majority of integer arithmetic codes do not need this. In most cases, throwing an exception for "division by zero" is just fine and slows down by an order of magnitude in all integer arithmetic operations ... is unacceptable.


In contrast to this:

  • "unused" values ​​in the presentation space already exist
  • The NaN and INF values ​​are part of the IEE floating point standard and
  • they are (usually) implemented using the embedded hardware implementation of floating point arithmetic
+4
source

As noted in other comments, this is mainly due to the fact that NaN is the default value for floating point numbers. You can read about the reasons NaN will be returned to Wikipedia here:

http://en.wikipedia.org/wiki/NaN

Note that there is only one of these reasons for integers (division by zero). There is also a positive and negative infinity value for floating point numbers that integers do not have and are closely related to NaN in the floating point specification.

0
source

Source: https://habr.com/ru/post/949313/


All Articles