Pregunta

I've experimented a curious behavior with divisions.

 some_nbr / 0    # >> ZeroDivisionError with 0 (Integer)
 some_nbr / 0.0  # => NaN with 0.0 (Float)

Of course, division by 0 is bad, but I'd like to figure out why doing a division by zero with an Integer results in an exception whereas doing the same with a float will just return Nan.

¿Fue útil?

Solución 2

Integer 0 is exactly zero; there is no error. And since division by zero is mathematically undefined, it makes sense that integer division by 0 raises an error.

On the other hand, float 0.0 is not necessarily representing exactly zero. It might originate from a number whose absolute value is small enough to be rounded to zero. In such case, mathematical division is still defined. It rather does not make sense to suddenly raise an error when the divisor's absolute value is small. However, in such case, a meaningful value cannot be reproduced due to the value being rounded, so the best it can be done to make sense is to return some sort of a pseudo-numeral, such as NaN.

Otros consejos

NaN and Infinity are "valid" Float values, in the sense that a memory address that holds a float can represent these values. This is part of the more general IEEE standard that ruby adopts.

In contrast, there are no valid representations for NaN or Infinity with Integers, therefore throwing an exception is appropriate.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top