Skip to content

Instantly share code, notes, and snippets.

@ishikawa
Created September 22, 2010 15:47
Show Gist options
  • Save ishikawa/591930 to your computer and use it in GitHub Desktop.
Save ishikawa/591930 to your computer and use it in GitHub Desktop.
SICP 1.1.7 "Squre Roots by Newton's Method"
;; SICP 1.1.7 "Squre Roots by Newton's Method"
;;
;; user=> (load-file "sicp/square-roots-by-newtons-method.clj")
;; #'user/sqrt
;; user=> sqrt
;; #<user$sqrt user$sqrt@1b0c6cfc>
;; user=> (sqrt 9)
;; 3.00009155413138
;; user=> (sqrt (+ 100 37))
;; 11.704699917758145
;; user=> (sqrt (+ (sqrt 2) (sqrt 3)))
;; 1.7739279023207892
;; user=> (square (sqrt 1000))
;; 1000.000369924366
(defn square [x] (* x x))
(defn abs
"The absolute-value procedure"
[x]
(cond (> x 0) x
(= x 0) 0
(< x 0) (- x)))
(defn good-enough?
[guess, x]
(< (abs (- (square guess) x)) 0.001))
(defn average [x y]
(/ (+ x y) 2))
(defn improve [guess x]
(average guess (/ x guess)))
(defn sqrt-iter [guess, x]
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x) x)))
(defn sqrt [x] (sqrt-iter 1.0 x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment