2

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)))
Busch
  • 857
  • 10
  • 29
  • Could you provide an example of how you are testing your function(s)? Also there are a few function definitions that are missing (at least `average` and `square`). – ponzao Nov 03 '13 at 20:48
  • I included the other helper functions above. An example call would be: (sqrt 1.4 2 0.01) – Busch Nov 03 '13 at 20:53
  • Shouldn't sqrt call next-guess at some point? – Alex Jasmin Nov 03 '13 at 21:30

1 Answers1

3

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
mishadoff
  • 10,719
  • 2
  • 33
  • 55