Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Square root (method by Hal Abelson in SICP MIT course) - Python and Scheme version.
def average(v1, v2):
return (v1 + v2) / 2.0
def square(n):
return n * n
def sqrt(n):
def improve(guess):
return average(guess, n / guess)
def good_enough(guess):
return abs(square(guess) - n) < 0.00000000001
def tryit(guess):
if good_enough(guess):
return guess
else:
return tryit(improve(guess))
return tryit(1)
(define average (lambda (v1 v2) (/ (+ v1 v2) 2)))
(define square (lambda (n) (* n n)))
(define (sqrt n)
(define (improve guess)
(average guess (/ n guess)))
(define (good-enough? guess)
(< (abs (- (square guess) n)) 0.0000000001))
(define (tryit guess)
(if (good-enough? guess)
guess
(tryit (improve guess))))
(tryit 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment