CprS376 Schedule
CprS376 Class 3
CprS376 Class 5

Formulating Abstractions with Higher-Order Procedures

Class 4 - Section 1.3



Contents

Fixed Points

; 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.4142135623746899

SICP Source Code

Programming Exercises

This will be the last class session dedicated to working on the following exercises from chapter 1: 5, 9, 10, 12,15, 17, 18, 29, 30, 31, 32, 34, 35, 36, 37.