Class 4 - Section 1.3
; fixed-point.ss ; SICP section 1.3.3 ; Chris Parrish ;; Fixed points (define tolerance 0.00001) (define (fixed-point f first-guess) (define (close-enough? v1 v2) (< (abs (- v1 v2)) tolerance)) (define (try guess) (let ((next (f guess))) (if (close-enough? guess next) next (try next)))) (try first-guess)) ;; fixed-point for cos (define fp (fixed-point cos 1.0)) ; => .7390822985224024 (abs (- (cos fp) fp)) ; => 4.744172929838086e-6 ;; fixed-point for another trigonometric function (define f (lambda (y) (+ (sin y) (cos y)))) (define fp (fixed-point f 1.0)) (abs (- (f fp) fp)) ; => 5.622822972783936e-6 ;; sqrt (define (bad-sqrt x) (fixed-point (lambda (y) (/ x y)) 1.0)) ;; don't try this at home, kids ; (bad-sqrt 2) (define (good-sqrt x) (fixed-point (lambda (y) (average y (/ x y))) 1.0)) (define (average a b) (/ (+ a b) 2)) (good-sqrt 2) ; => 1.4142135623746899SICP Source Code