Last active
December 31, 2015 19:39
-
-
Save toctan/8035022 to your computer and use it in GitHub Desktop.
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
| (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