2

我是 Clojure 的新手,正在尝试使用内置的迭代编写牛顿方法函数。我尝试了几件事导致以下代码。关于为什么这只是返回空括号的任何想法?我也对新想法持开放态度。

(defn within-tol? 
  "returns true if the guess is within the given tolerance"
  [guess x tolerance]
  (< (abs (- (square guess) x)) tolerance))

(defn next-guess 
  [guess x] 
  (average guess (/ x guess)))

(defn average
  [x y]
  (float (/ (+ x y) 2)))

(defn abs 
  [x]
  (cond
    (< x 0) (- x)
    :else x))

(defn square 
  [x]
  (* x x))

 (defn sqrt-iter
  [guess x tolerance]
  (if (within-tol? guess x tolerance) guess
    (sqrt-iter (next-guess guess x) x tolerance)))

 (defn sqrt 
   [guess x tolerance]
   (take-while #(within-tol? % x tolerance) (iterate #((sqrt % x tolerance)) guess)))
4

1 回答 1

3

似乎你sqrt错了,因为它不使用next-guess

试试看

(defn sqrt 
  [guess x tolerance]
  (first (drop-while #(not (within-tol? % x tolerance))
                     (iterate #(next-guess % x) guess))))

例子:

(sqrt 1 169 0.01) => 13.0
于 2013-11-03T21:33:18.143 回答