Exercise 1.39 of SICP

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

$$ \tan x = \cfrac{x}{1-\cfrac{x^2}{3-\cfrac{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.

(define (tan-cf x k)
  (define (n i)
    (if (= i 1)
      x
      (* x x)))
  (define (d i)
    (- (* 2 i) 1))
  (define (cf i)
    (if (= i (+ k 1))
      0
      (/ (n i) 
         (- (d i) (cf (+ i 1))))))
  (if (not (> k 0))
    0
    (cf 1)))
> (tan-cf (sqrt 2) 12)
6.334119167042199

$$ \tan \sqrt 2 = 6.3341191670421915540568332642277 $$