2011-09-17

SICP Exercise 1.39: Calculating tan x as a k-Term Continued Fraction

A continued fraction representation of the tangent function was published in 1770 by the German mathematician J.H. Lambert:
tan x =       x       
        1 -     x2    
            3 -   x2  
                5 - ⋱
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.

Okay, so let's have a look at how we can define Ni and Di so that we can use cont-frac to approximate the tangent function. For Ni we want N1 to be x and all other values to be -x2. For Di the sequence is 1, 3, 5, 7, .... I.e. 2i - 1. So producing tan-cf is nice and straightforward:
(define (tan-cf x k)
  (cont-frac (lambda (i) (if (= i 1)
                             x
                             (- (square x))))
             (lambda (i) (- (* 2 i) 1))
             k))
Here I'm assuming we still have square kicking around from earlier exercises.

We can see how good an approximation we get for various values of x and k by comparing our approximations with the build-in procedure tan:
> (tan 1)
1.5574077246549023
> (tan-cf 1.0 1)
1.0
> (tan-cf 1.0 2)
1.4999999999999998
> (tan-cf 1.0 3)
1.5555555555555558
> (tan-cf 1.0 4)
1.5573770491803278
> (tan-cf 1.0 5)
1.5574074074074076
So k = 5 gives us tan 1 to within 5 decimal places.

Of course if we set k large enough our approximations get more and more accurate:
> (tan 0.5)
0.5463024898437905
> (tan-cf 0.5 100)
0.5463024898437905

No comments:

Post a Comment