from sympy import *
from sympy import log,sin,exp
import math #定义变量为x
x=Symbol("x") #函数为
def taylor (f = x**4,n = 10,x0 = 0,t = 2):
#n = 100 #泰勒展开项数
i = 0
F = list()
#n阶导
while i <= n:
f1 = diff(f,x,i)
value = f.evalf(subs={x: x0})
F.append(value)
i = i+1
print (F)
#求阶乘
M = list()
for i in range (n+1):
if i == 0:
M.append(1)
else:
for j in range(i):
if j == 0:
v = 1
else:
v = v*(j+1)
M.append(v)
print (M)
#求(x - x0)^i
J = list()
for i in range(n+1):
v = (t - x0)**i
J.append(v)
print (J)
V = list()
for i in range(n+1):
value = J[i]/M[i]*F[i]
V.append(value)
return sum(V)
def main():
f = exp(x)
n = int(input('请输入泰勒展开项数'))
x0 = int(input('请输入x0'))
t = int(input('请输入x'))
value = f.evalf(subs={x: t})
predict = taylor(f,n,x0,t)
print (value)
print (predict)
main()
默认f(x) = exp(x)
请输入泰勒展开项数10
请输入x02
请输入x9
[7.38905609893065, 7.38905609893065, 7.38905609893065, 7.38905609893065, 7.38905609893065, 7.38905609893065, 7.38905609893065, 7.38905609893065, 7.38905609893065, 7.38905609893065, 7.38905609893065]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
[1, 7, 49, 343, 2401, 16807, 117649, 823543, 5764801, 40353607, 282475249]
8103.08392757538
7304.76166428328
请输入泰勒展开项数10
请输入x05
请输入x9
[148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
[1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576]8103.08392757538
8080.07306436618
可见泰勒公式的近似值与x0无关
/usr/bin/python3.5 /home/rui/ComputerScience/PythonProjects/数值分析/Taylor.py
请输入泰勒展开项数100
请输入x05
请输入x9
[148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 148.413159102577, 1