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:

\tan x = \frac{x}{1 - \frac{x^2}{3 - \frac{x^2}{5 - \ddots}}}

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:

 

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:


 

Output:

0.0
 

Output:

0

Here's an approximation of π:

 

Output:

0.999999998205103
 

Output:

0.999999998205103
 

Output:

-1.00000000538469
 

Output:

-1.00000000539582


Looks good. Values near a multiple of π (i.e., those for which tan x is nearly or exactly zero) need more iterations:

 

Output:

-3.58979302983757e-09
 

Output:

-5.48300699971479e-09
 

Output:

-3.58979298522367e-09
Personal tools