Skip to content

Commit

Permalink
Improve tests and fix error with recent Java
Browse files Browse the repository at this point in the history
When moving to Java 17 some of the tests started failing.
It turns out it was because `Math/abs` was being used instead of `abs`
in the Clojure branch of `same.platform/bit-diff-double` and `bit-diff-float`.
For large differences this would overflow, so `(bit-diff-double 1.0 2.0)` would
return 0 instead of a large number.
  • Loading branch information
emlyn committed Feb 12, 2025
1 parent ae878a3 commit 13285a6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
8 changes: 4 additions & 4 deletions src/same/platform.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@
(defn bit-diff-double
"Difference between two doubles in ULPs (i.e. number of representable numbers between them + 1)."
[f1 f2]
#?(:clj (Math/abs ^long (- (Double/doubleToLongBits f1)
(Double/doubleToLongBits f2)))
#?(:clj (abs (- (Double/doubleToLongBits f1)
(Double/doubleToLongBits f2)))
:cljs (let [buf (js/ArrayBuffer. 16)
dv (js/DataView. buf)]
(.setFloat64 dv 0 (double f1))
Expand All @@ -90,8 +90,8 @@
(defn bit-diff-float
"Difference between two floats in ULPs (i.e. number of representable numbers between them + 1)."
[f1 f2]
#?(:clj (Math/abs ^long (- (Float/floatToIntBits f1)
(Float/floatToIntBits f2)))
#?(:clj (abs ^long (- (Float/floatToIntBits f1)
(Float/floatToIntBits f2)))
:cljs (let [buf (js/ArrayBuffer. 8)
dv (js/DataView. buf)]
(.setFloat32 dv 0 (float f1))
Expand Down
20 changes: 19 additions & 1 deletion test/same/platform_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,23 @@
(is (p/nan? (p/ulp nan))))

(deftest bit-diff-double-test
(is (zero? (p/bit-diff-double 1.0 1.0)))
(is (= 1 (p/bit-diff-double 1.0 1.0000000000000002)))
(is (= 1 (p/bit-diff-double 1.0000000000000002 1.0))))
(is (= 1 (p/bit-diff-double 1.0000000000000002 1.0)))
(is (= 0x8000000000000 (p/bit-diff-double 1.0 1.5)))
(is (= 0x8000000000000 (p/bit-diff-double 1.5 1.0)))
(is (= 0x10000000000000 (p/bit-diff-double 1.0 2.0)))
(is (= 0x10000000000000 (p/bit-diff-double 2.0 1.0)))
(is (= 0x100000000000000 (p/bit-diff-double 1.0 65536.0)))
(is (= 0x100000000000000 (p/bit-diff-double 65536.0 1.0))))

(deftest bit-diff-float-test
(is (zero? (p/bit-diff-float 1.0 1.0)))
(is (= 1 (p/bit-diff-float 1.0 1.0000001)))
(is (= 1 (p/bit-diff-float 1.0000001 1.0)))
(is (= 0x400000 (p/bit-diff-float 1.0 1.5)))
(is (= 0x400000 (p/bit-diff-float 1.5 1.0)))
(is (= 0x800000 (p/bit-diff-float 1.0 2.0)))
(is (= 0x800000 (p/bit-diff-float 2.0 1.0)))
(is (= 0x8000000 (p/bit-diff-float 1.0 65536.0)))
(is (= 0x8000000 (p/bit-diff-float 65536.0 1.0))))

0 comments on commit 13285a6

Please sign in to comment.