Why is division by cero treated diferent on Doubles and Ints?


#1

I was making some test using the scala REPL and I found the following interesting result.

scala> 0/0
java.lang.ArithmeticException: / by zero
  ... 28 elided

scala> 0.0/0.0
res9: Double = NaN

Why does dividing by zero cause an exception on integers but a NaN on doubles? I have supposed that it is because of the floating-point standard but I can’t find an answer about it.


#2

https://en.wikipedia.org/wiki/IEEE_754

IEEE 754 standard defines the floating point behavior that the JVM’s standard libs (which undergird Scala’s standard libs) try to follow.

Brian Maso


#3

You get same behaviour in C/ C++: https://www.ideone.com/Zv7CcA i.e. in C division by floating point zero results in NaN, but division by fixed point zero results in fault. Note that in C you need to make zeros dynamic (e.g. by reading them from standard input), not constants, because otherwise compiler will do the division in compile time.

Scala does what Java does, most probably because it doesn’t want to add overhead. In turn, Java does what C/ C++ does probably to avoid surprises for C/ C++ developers coming to Java. Remember that in the beginning C/ C++ developers were main marketing target for Java.


#4

The different treatment of floating points and integers goes down all the way to hardware support.

The deeper reason is that floating points are already complex and expensive data types mostly used to crunch applied math, science and engineering data, so the cost of adding special values and extra checks is easy to justify.

Integers, on the other hand, are inherently simple and easy to compute data types, and they are used everywhere down to basic system tasks, so you want them as efficient as possible, including no special values. For example, by default, there are no checks for overflow, either.