ę³°åęå¼Ā¶
äøē§åå°ē±³ē¹ęå¼
使ēØę³°åå ¬å¼åØ$x_0$å¤å±å¼å¾å°å¤é”¹å¼
$$ P_n(x)=\sum_{k=0}^{n} \frac{f^{(k)}(x_0)}{k!}(x-x_0)^{k} $$
ä¾å¶
äøé¢ēä¾åęÆ$e^x$å$ln(x)$ēę³°åęå¼ęØ”ę
åÆä»„ēå°$e^x$åØ$x=0$åŗå±å¼ēę³°åēŗ§ę°ēę¶ęåęÆ$(-\infty, \infty)$ļ¼å±å¼ēꬔę°$n$č¶å¤§å¤é”¹å¼å½ę°č¶ę„čæåå½ę°
$ln(x)$åØ$x=1$ę¶å±å¼ēę³°åēŗ§ę°ēę¶ęåęÆ$(0, 2]$ļ¼äøéē$n$č¶å¤§å¤é”¹å¼å½ę°åØč¶ åŗę¶ęåę¶ä¼äøäøęåØ
InĀ [76]:
import sympy as sp
def taylor(_f, df, x0, n):
def p(x):
res = _f(x0)
dd = 1 #é¶ä¹
w = 1
for i in range(1, n + 1):
dd *= i
w *= (x - x0)
df_res = df(i, x0)
res += (df_res * w / dd)
return res
return p
InĀ [77]:
import numpy as np
import math
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 400)
y = np.exp(x)
plt.plot(x, y, '-', label=r'$e^x$')
def df(n, x0):
return math.exp(x0)
p = taylor(math.exp, df, 0, 5)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$P_n(x), n=5$')
p = taylor(math.exp, df, 0, 10)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$P_n(x), n=10$')
p = taylor(math.exp, df, 0, 13)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$P_n(x), n=13$')
p = taylor(math.exp, df, 0, 15)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$P_n(x), n=15$')
plt.title('Taylor Expand')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid()
plt.show()
InĀ [78]:
import numpy as np
import math
import matplotlib.pyplot as plt
x = np.linspace(0, 3, 100)[1:]
y = np.log(x)
x0 = 1
plt.plot(x, y, '-', label=r'$ln(x)$')
def df(n, x0):
return (-1) ** (n - 1) * math.factorial(n - 1) / (x0 ** n)
p = taylor(math.log, df, x0, 5)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$P_n(x), n=5$')
p = taylor(math.log, df, x0, 10)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$P_n(x), n=10$')
p = taylor(math.log, df, x0, 13)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$P_n(x), n=13$')
p = taylor(math.log, df, x0, 15)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$P_n(x), n=15$')
p = taylor(math.log, df, x0, 16)
p_f = np.vectorize(p)
y_1 = p_f(x)
plt.plot(x, y_1, '-', label=r'$P_n(x), n=16$')
plt.ylim(-10, 10)
plt.xlim(0, 3)
plt.title('Taylor Expand')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid()
plt.show()