Skip to content

Instantly share code, notes, and snippets.

@toctan
Last active December 31, 2015 19:39
Show Gist options
  • Select an option

  • Save toctan/8035022 to your computer and use it in GitHub Desktop.

Select an option

Save toctan/8035022 to your computer and use it in GitHub Desktop.
(define (sqrt x)
(define tolerance 0.00001)
(define (good-enough? y)
(< (abs (- (square y) x))
tolerance))
(define (improve y)
(average (/ x y) y))
(define (try y)
(if (good-enough? y)
y
(try (improve y))))
(try 1))
(define (fixed-point improve i)
(define tolerance 0.00001)
(define (close-enough? old new)
(< (abs (- old new)) tolerance))
(define (iter old new)
(if (close-enough? old new)
new
(iter new (improve new))))
(iter i (improve i)))
(define (average-damp f)
(lambda (x) (average (f x) x)))
(define (sqrt x)
(fixed-point
(average-damp (lambda(y) (/ x y)))
1))
;; Newton's method
(define (sqrt x)
(newton (lambda(y) (- x (square y)))
1))
(define (newton f i)
(define df (deriv f))
(fixed-point
(lambda(x) (- x (/ (f x) (df x))))
i))
(define (deriv f)
(define dx 0.000001)
(lambda(x) (/ (- (f (+ x dx))
(f x))
dx)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment