Note: this wiki is now retired and will no longer be updated!

The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.

SICP exercise 1.39

From Drewiki
Jump to: navigation, search

Problem

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

<math>\tan x = \frac{x}{1 - \frac{x^2}{3 - \frac{x^2}{5 - \ddots}}}</math>

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.

Solution

Here's one implementation of Lambert's continued fraction representation of the tangent function, using the cont-frac function from exercise 1.37:

(define (cont-frac n d k)
  (define (cont-frac-iter k result)
    (if (= k 0)
        result
        (cont-frac-iter (- k 1) (/ (n k) (+ (d k) result)))))
  (cont-frac-iter k 0))
 
(define (square x) (* x x))
 
(define (tan-cf x k)
  (define (n k)
    (if (= k 1)
        x
        (- (square x))))
  (define (d k)
    (- (* 2 k) 1))
  (cont-frac n d k))

We can test the procedure by comparing the results to the tan primitive provided by Chicken Scheme 3.1 on a MacBook Pro running Mac OS X 10.5:


(tan 0)

Output:

0.0
(tan-cf 0 10)

Output:

0

Here's an approximation of <math>\pi</math>:

(define pi 3.14159265)
 
(tan (/ pi 4))

Output:

0.999999998205103
(tan-cf (/ pi 4) 10)

Output:

0.999999998205103
(tan (/ (* 3 pi) 4))

Output:

-1.00000000538469
(tan-cf (/ (* 3 pi) 4) 10)

Output:

-1.00000000539582


Looks good. Values near a multiple of <math>\pi</math> (i.e., those for which tan x is nearly or exactly zero) need more iterations:

(tan pi)

Output:

-3.58979302983757e-09
(tan-cf pi 10)

Output:

-5.48300699971479e-09
(tan-cf pi 20)

Output:

-3.58979298522367e-09
Personal tools