-
Notifications
You must be signed in to change notification settings - Fork 1
/
Exercise 1.39 Lambert's Formula.rkt
executable file
·98 lines (82 loc) · 2.17 KB
/
Exercise 1.39 Lambert's Formula.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#lang racket
; Exercise 1.39. A continued fraction representation of the tangent function was published in
; 1770 by the German mathematician J.H. Lambert:
; x
; tan x = ------------------
; 1 - x^2
; ------------
; 3 - x^2
; ------
; 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.
; (a) Recursive
(define (cont-frac-recur n d k)
(define (cont-frac-recur-internal n d k i)
(if (< i k)
(/ (n i) (+ (d i) (cont-frac-recur-internal n d k (+ i 1))))
(/ (n i) (d i))
)
)
(cont-frac-recur-internal n d k 1)
)
; (b) Iterative
(define (cont-frac-iter n d k)
; No deferred calcualtions so we need to work in the reverse direction to the
; recursive process
(define (basic-op a b c)
(+ a (/ b c))
)
(define (cont-frac-iter-internal n d iters accumulator)
(cond
((= iters k) (cont-frac-iter-internal n d (- iters 1) (basic-op (d (- k 1)) (n k) (d k))))
((and (< iters k) (> iters 1)) (cont-frac-iter-internal n d (- iters 1) (basic-op (d (- iters 1)) (n iters) accumulator)))
((= iters 1) (/ (n 1) accumulator))
)
)
(cont-frac-iter-internal n d k 0)
)
(define (tan-cf x k)
(cont-frac-recur
(lambda (i)
(if (= i 1)
x
(- 0.0 (square x)) ; return the negative of the square
)
)
(lambda (i) (- (* 2 i) 1))
k
)
)
(define (square x)
(* x x)
)
; Tests
> (tan-cf 0 10)
0
> (tan-cf pi 10)
-1.893214149359168e-009
> (tan-cf (/ pi 4) 10)
1.0
> (tan-cf (/ pi 2) 10)
744656605476677.9
> (tan-cf (/ pi 3) 10)
1.732050807568877
> (tan-cf (/ pi 3) 100)
1.732050807568877
> (tan-cf (/ pi 3) 5)
1.7320501979592633
> (tan-cf (/ (* 2 pi) 3) 5)
-1.7329572186349194
> (tan-cf (/ pi 6) 20)
0.5773502691896257
> (tan-cf (/ (* 5 pi) 6) 20)
-0.5773502691896255
> (tan-cf (/ (* 5 pi) 6) 200)
-0.5773502691896255
> (tan-cf (/ (* 5 pi) 6) 2000)
-0.5773502691896255
> (tan-cf (/ (* 3 pi) 4) 10)
-1.0000000000111287
>