Skip to content

Instantly share code, notes, and snippets.

@josephmosby
Last active August 29, 2015 14:06
Show Gist options
  • Save josephmosby/d8efc2afc33a7783210f to your computer and use it in GitHub Desktop.
Save josephmosby/d8efc2afc33a7783210f to your computer and use it in GitHub Desktop.
Mechanisms for describing a square root function, from MIT
(define (average x y)
(/ (+ x y) 2))
(define (improve guess x)
(average guess (/ x guess)))
(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001))
(define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x) x )))
(define (sqrt x)
(sqrt-iter 1.0 x))
// improvement, with proper block scoping
(define (sqrt x)
(define (good-enough? guess)
(< (abs (- (square guess) x)) 0.001))
(define (improve guess)
(average guess (/ x guess)))
(define (sqrt-iter guess)
(if (good-enough? guess)
guess
(sqrt-iter (improve guess))))
(sqrt-iter 1.0 x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment