SICP-2nd-Edition-Exercise-1.37

From Boozled

Jump to: navigation, search

Contents

Exercise 1.37 From SICP

Details from SICP are here

a. An infinite continued fraction is an expression of the form

f = \cfrac{N_1}{D_1 + \cfrac{N_2}{D_2 + \cfrac{N_3}{D_3 \ldots\,}}}

As an example, one can show that the infinite continued fraction expansion with the Ni and the Di all equal to 1 produces 1 / φ, where φ is the golden ratio (described in section 1.2.2). One way to approximate an infinite continued fraction is to truncate the expansion after a given number of terms. Such a truncation -- a so-called k-term finite continued fraction -- has the form

f = \cfrac{N_1}{D_1 + \cfrac{N_2}{\ddots + \cfrac{N_K}{D_K}}}

Suppose that n and d are procedures of one argument (the term index i) that return the Ni and Di of the terms of the continued fraction. Define a procedure cont-frac such that evaluating (cont-frac n d k) computes the value of the k-term finite continued fraction. Check your procedure by approximating 1 / φ using

  1. (cont-frac (lambda (i) 1.0)
  2.            (lambda (i) 1.0)
  3.            k)

for successive values of k. How large must you make k in order to get an approximation that is accurate to 4 decimal places?

b. If your cont-frac procedure generates a recursive process, write one that generates an iterative process. If it generates an iterative process, write one that generates a recursive process.

Attempt

Part b needs to be done yet.

Scheme

  1. (define (cont-frac n d k)
  2.   (define (iter k res)
  3.     (display "k=")  (display k)   (newline)
  4.     (display "res=")(display res) (newline)
  5.     (let ((res (+ (d (- k 1)) (/ (n k) res) )))
  6.       (if (< k 1)
  7.       res
  8.       (iter (- k 1) res)))) 
  9.   (iter k 1))
  10.  
  11. (define k 11)
  12. (display (cont-frac (lambda (x) 1.0) (lambda (x) 1.0) k))

Parent Course

6.001_Structure_and_Interpretation_of_Computer_Programs

Further Reading

Personal tools