my attempt to do the exercises in sicp.

Tuesday, July 1, 2008

sicp exercise 1.39


;  Exercise 1.39.  A continued fraction representation of the tangent function was published in 1770
;  by the German mathematician J.H. Lambert:

;
;  where x is in radians. Define a procedure (tan-cf x k) that computes an approximation to the
;  tangent function based on Lambert's formula. K specifies the number of terms to compute, as
;  in exercise 1.37.


(define (cont-frac-iter n d k)
    (define (iter i result)
       (if (= i 0)
           result
           (iter (- i 1) (/ (n i) (+ (d i) result)))))
    (iter k 0))


(define (square y) (* y y))
(define (tan x k)
   (define N (square x))
   (define (n i) (if (= i 1) x (- N)))
   (define (d i) (- (* i 2) 1))
   (cont-frac-iter n d k))


(define pi 3.141592653589793116)
(display (tan (/ pi 4) 100)) (newline)
(display (tan (/ pi 2) 100)) (newline)

No comments: