Write a program that uses your cont-frac procedure from exercise 1.37 to approximate e, based on Euler's expansion.The main challenge with this exercise is how to caputure the series 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, .... as a procedure.
- f(x) = x for 1 and 2
- For x > 2, every third term is part of the series 4, 6, 8, ...
- For every other x, f(x) = 1
remainder
to check whether the argument is one of those third terms. If it is, its value is 2 greater than the term for x - 3. Or to put it another way, f(x) = 2 + f(x - 3), for x = 5, 8, 11....;; Exercise 1.38 (define (d x) (cond ((< x 3) x) ((= 0 (remainder (- x 2) 3)) (+ 2 (d (- x 3)))) (else 1))) (+ 2 (cont-frac d (lambda (x) 1.0) 100)) ;Value: 2.7182818284590455
Exercise 1.39
Define a procedure (tan-cf x k)
that computes an approximation to the tangent function based on Lambert's formula.
A few points I had to keep in mind:- Procedure n has to operate on the argument x, but n should still take only one value, which is the term for that portion of the contiued fraction.
- Procedure n returns a number, which is the value of an appropriate procedure applied to x.
- Procedure n should return a negative number for values of k greater than 1.
;; Exercise 1.38 (define (tan-cf x k) (define (d i) (if (= i 1) 1.0 (+ 2 (d (- i 1))))) (define (n i) (if (= i 1) x (- (* x x)))) (cont-frac d n k))
Comparing my results with the calculator result of tan(3) = -0.142546543074278:
;; Using recursive version of cont-frac (tan-cf 3 10) ;Value: -.1425465438397583 ; Using iterative Version of cont-frac (tan-cf 3 10) ;Value: -.14254654300801906
Finally, testing these two exercises revealed an error in my solution for exercise 1.37 (since corrected).