Created
September 22, 2010 15:47
-
-
Save ishikawa/591930 to your computer and use it in GitHub Desktop.
SICP 1.1.7 "Squre Roots by Newton's Method"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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