我需要撰寫一個能顯示函式的泰勒公式,代碼如下
import sympy as sy
import numpy as np
from sympy.functions import sin,cos
# Define the variable and the function to approximate
x = sy.Symbol('x')
# Factorial function
def factorial(n):
if n <= 0:
return 1
else:
return n*factorial(n-1)
# Taylor approximation at x0 of the function 'function'
def taylor(function,x0,n):
i = 0
p = 0
for i in range (0,n+1):
p = p + (function.diff(x,i).subs(x,x0))/(factorial(i))*(x-x0)**i
return p
運行比如輸入 taylor(x**3,3,3)得到的結果是
27*x + (x - 3)**3 + 9*(x - 3)**2 - 54
而不是正確答案
27+27*x+9*(x - 3)**2+(x - 3)**3
請大佬看一下代碼哪里出錯了。非常感謝!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/167097.html
上一篇:Python for 回圈的優化
下一篇:那個大佬可以幫下
