2013-07-17 34 views

回答

8

你需要确定 “关闭”。如果你问一个小于一些宽容“差”,则可以使用<推出自己的功能:

(defn close? [tolerance x y] 
    (< (difference x y) tolerance)) 

凡差异可能是绝对的:

(defn absolute-difference ^double [^double x ^double y] 
    (Math/abs (double (- x y)))) 

或相对:

(defn relative-difference ^double [^double x ^double y] 
    (/ (Math/abs (- x y)) 
    (max (Math/abs x) (Math/abs y)))) 

(当然,选择你的首选定义的相对差异)。

然后(partial close? 0.001)将测试近似相等与容差0.001。

要发现公差参数有用值的限制,您可以使用Math/ulp,这是一种静态方法,它采用double并返回它与最小的较大double之间的绝对差值。

5

虽然我喜欢米哈尔Marczyk的溶液,请注意,已经有

在clojure.algo.generic.math函数定义的约=

功能。样品用法:

clojuree.o=> (approx= 1.41 (sqrt 2) 1e-2) 
true 
clojuree.o=> (approx= 1.41 (sqrt 2) 1e-4) 
false 
相关问题