总所周知,我们可以使用泰勒级数来表示一个函数:
如果
f
(
x
)
f(x)
f(x)在点
x
=
x
0
x=x_0
x=x0具有任意阶导数,则幂级数
∑
n
=
0
∞
f
(
n
)
(
x
0
)
n
!
(
x
−
x
0
)
n
\sum_{n=0}^{\infty}{\frac{f^{(n)}(x_0)}{n!}(x-x_0)^n}
n=0∑∞n!f(n)(x0)(x−x0)n
称为
f
(
x
)
f(x)
f(x)在点
x
=
x
0
x=x_0
x=x0处的泰勒级数。
若取
x
0
=
0
x_0=0
x0=0,得到的级数
∑
n
=
0
∞
f
(
n
)
(
0
)
n
!
x
n
\sum_{n=0}^{\infty}{\frac{f^{(n)}(0)}{n!}x^n}
n=0∑∞n!f(n)(0)xn
称为麦克劳林级数。
例如,对于
f
(
x
)
=
e
x
f(x)=e^x
f(x)=ex,我们有
e
x
=
∑
n
=
0
∞
x
n
n
!
=
x
0
0
!
+
x
1
1
!
+
⋯
.
e^x=\sum_{n=0}^{\infty}{\frac{x^n}{n!}}=\frac{x^0}{0!}+\frac{x^1}{1!}+\cdots.
ex=n=0∑∞n!xn=0!x0+1!x1+⋯.
同时,
e
e
e的极限定义为:
e
=
lim
n
→
0
(
1
+
n
)
1
n
.
e=\lim_{n\rightarrow 0}{(1+n)^{\frac{1}{n}}}.
e=n→0lim(1+n)n1.
由此,我们可以通过麦克劳林级数以及极限的方法来逼近自然底数
e
e
e。
from math import factorial
def maclaurin(n: int) -> float:
"""Calculates the nth term of the Maclaurin series for e."""
res = 0
for i in range(n + 1):
res += 1 ** i / factorial(i)
return res
def limit(n: float) -> float:
"""Calculates the limit for e."""
return (1 + n) ** (1 / n)
if __name__ == '__main__':
# Calculate e using different ways (the output may be different on different computers).
print(maclaurin(10000)) # Output: 2.7182818284590455
print(limit(0.0001)) # Output: 2.7181459268249255