泰勒展开¶
这里统一在$x_0=0$处展开也就是展开成麦克劳林级数
In [19]:
# e^x展开
def exp_taylar_expand(x, n, showLog = False):
res = 1
k = 1
xx = x
for i in range(1, n + 1):
k *= i
res += (xx / k)
xx *= x
if showLog:
print(f'第{i}次迭代值 {res}')
return res
exp_taylar_expand(1, 20, True)
第1次迭代值 2.0 第2次迭代值 2.5 第3次迭代值 2.6666666666666665 第4次迭代值 2.708333333333333 第5次迭代值 2.7166666666666663 第6次迭代值 2.7180555555555554 第7次迭代值 2.7182539682539684 第8次迭代值 2.71827876984127 第9次迭代值 2.7182815255731922 第10次迭代值 2.7182818011463845 第11次迭代值 2.718281826198493 第12次迭代值 2.7182818282861687 第13次迭代值 2.7182818284467594 第14次迭代值 2.71828182845823 第15次迭代值 2.718281828458995 第16次迭代值 2.718281828459043 第17次迭代值 2.7182818284590455 第18次迭代值 2.7182818284590455 第19次迭代值 2.7182818284590455 第20次迭代值 2.7182818284590455
Out[19]:
2.7182818284590455
In [23]:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10, 10, 400)
y = np.exp(x)
plt.plot(x, y, '-', label=r'$e^x$')
p_f = np.vectorize(exp_taylar_expand)
y = p_f(x, 10)
plt.plot(x, y, '-', label=r'$P_n(x), n=10$')
y = p_f(x, 12)
plt.plot(x, y, '-', label=r'$P_n(x), n=12$')
y = p_f(x, 14)
plt.plot(x, y, '-', label=r'$P_n(x), n=14$')
plt.title('Taylor Expand')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid()
plt.show()
In [36]:
# ln((1 + x) / (1 - x))展开
def artanh_taylar_expand(x, n_terms, showLog = False):
result = 0.0
for n in range(n_terms):
exponent = 2 * n + 1
term = (x ** exponent) / exponent
result += term
if showLog:
print(f'第{n + 1}次迭代值 {2 * result}')
return 2 * result, result
artanh_taylar_expand(1 / 3, 20, True)
第1次迭代值 0.6666666666666666 第2次迭代值 0.691358024691358 第3次迭代值 0.6930041152263374 第4次迭代值 0.6931347573322881 第5次迭代值 0.6931460473908271 第6次迭代值 0.6931470737597851 第7次迭代值 0.6931471702560119 第8次迭代值 0.6931471795482411 第9次迭代值 0.693147180459244 第10次迭代值 0.6931471805498115 第11次迭代值 0.6931471805589162 第12次迭代值 0.6931471805598399 第13次迭代值 0.6931471805599343 第14次迭代值 0.693147180559944 第15次迭代值 0.693147180559945 第16次迭代值 0.6931471805599451 第17次迭代值 0.6931471805599451 第18次迭代值 0.6931471805599451 第19次迭代值 0.6931471805599451 第20次迭代值 0.6931471805599451
Out[36]:
(0.6931471805599451, 0.34657359027997253)
In [44]:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 100)
y = np.arctanh(x)
plt.plot(x, y, '-', label=r'$arctanh(x)$')
p_f = np.vectorize(artanh_taylar_expand)
_, y = p_f(x, 2)
plt.plot(x, y, '-', label=r'$P_n(x), n=2$')
_, y = p_f(x, 4)
plt.plot(x, y, '-', label=r'$P_n(x), n=4$')
_, y = p_f(x, 6)
plt.plot(x, y, '-', label=r'$P_n(x), n=6$')
_, y = p_f(x, 10)
plt.plot(x, y, '-', label=r'$P_n(x), n=10$')
plt.title('Taylor Expand')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid()
plt.show()
/tmp/ipykernel_4595/3092700043.py:5: RuntimeWarning: divide by zero encountered in arctanh y = np.arctanh(x)