ę³°å‹’ę’å€¼Ā¶

äø€ē§åŸƒå°”ē±³ē‰¹ę’å€¼

ä½æē”Øę³°å‹’å…¬å¼åœØ$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()
No description has been provided for this image
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()
No description has been provided for this image