What is the idiomatic way to test if two numbers are close to each other in Clojure?
Somewhere along the line of:
(deftest sqrt-test
(is (~= 1.414 (Math/sqrt 2)))
You'll need to define "close". If you ask for a "difference" of less than some tolerance, you can roll your own function using <
:
(defn close? [tolerance x y]
(< (difference x y) tolerance))
Where difference might be absolute:
(defn absolute-difference ^double [^double x ^double y]
(Math/abs (double (- x y))))
or relative:
(defn relative-difference ^double [^double x ^double y]
(/ (Math/abs (- x y))
(max (Math/abs x) (Math/abs y))))
(pick your preferred definition of relative difference, of course).
Then (partial close? 0.001)
will test approximate equality with tolerance of 0.001.
To discover limits on useful values of the tolerance parameter you can use Math/ulp
, which is a static method which takes a double and returns the absolute difference between it and the smallest larger double.
Although I like the solution of Michał Marczyk, note that there already is
approx=
function defined in clojure.algo.generic.math-functions. Sample usage:
clojuree.o=> (approx= 1.41 (sqrt 2) 1e-2)
true
clojuree.o=> (approx= 1.41 (sqrt 2) 1e-4)
false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With