Clojure

divide(Object, Object) with (NaN, 0) does not return NaN

Details

  • Type: Defect Defect
  • Status: Reopened Reopened
  • Priority: Trivial Trivial
  • Resolution: Unresolved
  • Affects Version/s: None
  • Fix Version/s: None
  • Component/s: None
  • Labels:

Description

user=> (def x Double/NaN)
#'user/x
user=> (/ x 0)

ArithmeticException Divide by zero clojure.lang.Numbers.divide (Numbers.java:156)
user=> (/ Double/NaN 0)
Double/NaN

Activity

Hide
Alex Miller added a comment -

As per the Java Language Specification (http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.4),

"All numeric operations with NaN as an operand produce NaN as a result."

Show
Alex Miller added a comment - As per the Java Language Specification (http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.4), "All numeric operations with NaN as an operand produce NaN as a result."
Hide
Yongqian Li added a comment -

But in the first example it produces an ArithmeticException.

Show
Yongqian Li added a comment - But in the first example it produces an ArithmeticException.
Hide
Alex Miller added a comment -

Ah, I see the question now.

Here we are dividing a double by a long. In the first case, this is parsed as divide(Object, long) which then calls divide(Object, Object), which throws ArithmeticException if the second arg is 0 (regardless of the first arg).

In the second case it's parsed as divide(double, long) which just relies on Java to properly upcast the primitive long to a double to do the divide.

Note that making this call with 2 doubles does return NaN:

user=> (def x Double/NaN)
#'user/x
user=> (/ x 0.0)
NaN

or type hinting x to a double works as well:

user=> (def x Double/NaN)
#'user/x
user=> (/ ^double x 0.0)
NaN

I think one option to "fix" this behavior would be to add checks in divide(Object, Object) to check whether x is NaN and instead return NaN.

Show
Alex Miller added a comment - Ah, I see the question now. Here we are dividing a double by a long. In the first case, this is parsed as divide(Object, long) which then calls divide(Object, Object), which throws ArithmeticException if the second arg is 0 (regardless of the first arg). In the second case it's parsed as divide(double, long) which just relies on Java to properly upcast the primitive long to a double to do the divide. Note that making this call with 2 doubles does return NaN:
user=> (def x Double/NaN)
#'user/x
user=> (/ x 0.0)
NaN
or type hinting x to a double works as well:
user=> (def x Double/NaN)
#'user/x
user=> (/ ^double x 0.0)
NaN
I think one option to "fix" this behavior would be to add checks in divide(Object, Object) to check whether x is NaN and instead return NaN.

People

Vote (0)
Watch (1)

Dates

  • Created:
    Updated: