Solution to SICP Exercise 1.37

Structure and Interpretation of Computer Programs

Solution to Exercise 1.37:

; part a (recursive process)
(define (cont-frac n d k)
(define (sub-expr i)
(if (= i k)
(/ (n i) (d i))
(/ (n i) (+ (d i) (sub-expr (+ i 1))))))
(sub-expr 1))

(define (golden-ratio k)
(cont-frac (lambda (i) 1.0)
(lambda (i) 1.0)
k))

(define (iterations-required)
(define (iter i previous)
(let ((current (golden-ratio i)))
(if (= (round (* current 10000))
(round (* previous 10000)))
(- i 1)
(iter (+ i 1) current))))
(iter 1 0.0))

; > (iterations-required)
; 12

; part b (iterative process)
(define (cont-frac-i n d k)
(define (iter i sub-expr)
(if (= i 0)
sub-expr
(iter (- i 1) (/ (n i) (+ (d i) sub-expr)))))
(iter (- k 1) (/ (n k) (d k))))

Advertisements