Search code examples
clojurenewtons-method

Iterate help in Clojure


I'm new to Clojure and am trying to write a Newton's method function using the built in iterate. I have tried several things that resulted in the following code. Any ideas as to why this is only returning empty parens? I'm open to new ideas as well.

(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)))

Solution

  • Seems your sqrt is wrong as it does not use next-guess

    Try that

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

    Example:

    (sqrt 1 169 0.01) => 13.0