Skip to content

Instantly share code, notes, and snippets.

@chelseatroy
Created October 29, 2019 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chelseatroy/7793b57444ae5e3750e5ebd137b7b651 to your computer and use it in GitHub Desktop.
Save chelseatroy/7793b57444ae5e3750e5ebd137b7b651 to your computer and use it in GitHub Desktop.
Iterative Square Root
(define (square x) (* x x))
(define (average x y)
(/ (+ x y) 2))
(define (sqrt x)
(define (improve guess)
(average guess (/ x guess)))
(define (good-enough? guess)
(< (abs (- (square guess) x)) (* 0.000001 x)))
(define (sqrt-iter guess)
(if (good-enough? guess)
guess
(sqrt-iter (improve guess)
)
))
(sqrt-iter 1.0)
)
(square (sqrt 9)) ; 3.000073824
(square (sqrt 0.0001)) ; 0.000100213
(square (sqrt 845000000000)) ; 845000004201
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment