用Racket计算泰勒级数展开

自然指数函数的泰勒级数展开:
$$ e^x = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \cdots $$

正弦函数的泰勒级数展开:
$$ \sin(x) = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots $$

余弦函数的泰勒级数展开:
$$ \cos(x) = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \cdots $$

自然对数的泰勒级数展开:
$$ \ln(1 + x) = x - \frac{x^2}{2} + \frac{x^3}{3} - \frac{x^4}{4} + \cdots $$

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
; 计算阶乘
(define (factorial n)
(if (= n 0) 1
(* n (factorial (- n 1)))))

; 泰勒级数展开:e^x
(define (exp-taylor x terms)
(if (= terms 0)
0
(+ (/ (expt x (- terms 1)) (factorial (- terms 1)))
(exp-taylor x (- terms 1)))))

; 泰勒级数展开:sin(x)
(define (sin-taylor x terms)
(if (= terms 0)
0
(let ([term-num (sub1 (* 2 terms))])
(+ (* (if (even? terms) -1 1) (/ (expt x term-num) (factorial term-num)))
(sin-taylor x (- terms 1))))))

; 泰勒级数展开:cos(x)
(define (cos-taylor x terms)
(if (= terms 0)
1
(let ([term-num (sub1 (* 2 terms))])
(+ (* (if (even? terms) 1 -1) (/ (expt x term-num) (factorial term-num)))
(cos-taylor x (- terms 1))))))

; 泰勒级数展开:ln(1 + x)
(define (ln-taylor x terms)
(if (= terms 0)
0
(+ (* (if (even? terms) -1 1) (/ (expt x terms) terms))
(ln-taylor x (- terms 1)))))

(exp-taylor 1 10) ; e^1 的近似值
(sin-taylor 1 10) ; sin(1) 的近似值
(cos-taylor 1 10) ; cos(1) 的近似值
(ln-taylor 0.5 10) ; ln(1.5) 的近似值