使用scipy.misc.derivative求泰勒系数报错:'float' object is not callable
问题:使用Scipy.misc.derivative求解泰勒级数系数时出现TypeError错误
我尝试用Scipy.misc的derivative函数求解泰勒级数的系数,但Scipy库内部一直报错。
我的代码:
d_pts = order*2 if d_pts % 2 == 0: # must be odd and greater than derivative order d_pts += 1 coefficients = [] for i in range(1, order+1): coefficients.append(round((derivative(function, center, n=i, order=d_pts))/math.factorial(i), 5)) return coefficients
错误信息:
<ipython-input-31-c44b369ecec2> in findCoefficients(function, order, center) 5 coefficients = [] 6 for i in range(1, order+1): ----> 7 coefficients.append(round((derivative(function, center, n=i, order=d_pts))/math.factorial(i), 5)) 8 return coefficients /usr/local/lib/python3.8/dist-packages/scipy/misc/common.py in derivative(func, x0, dx, n, args, order) 142 ho = order >> 1 143 for k in range(order): ---> 144 val += weights[k]*func(x0+(k-ho)*dx,*args) 145 return val / prod((dx,)*n,axis=0) 146 TypeError: 'float' object is not callable
问题原因与解决方法
错误原因
这个错误的核心是:你传入derivative函数的第一个参数function不是可调用的函数对象,而是一个浮点数。比如你可能误把某个函数的计算结果(例如function(center))传进了findCoefficients,而非函数本身。derivative需要调用传入的函数来计算数值导数,但浮点数无法被调用,因此抛出该错误。
解决方法
- 确保
function参数是可调用对象:传入的function必须是一个能接收单个参数并返回数值的函数,比如自定义函数、math模块下的函数(如math.sin),或者lambda表达式。 - 检查调用逻辑:调用
findCoefficients时,确认传递的第一个参数是函数本身,而不是函数执行后的返回值。
正确示例
import math from scipy.misc import derivative def findCoefficients(function, order, center): d_pts = order*2 if d_pts % 2 == 0: # 必须为奇数且大于导数阶数 d_pts += 1 coefficients = [] for i in range(1, order+1): coeff = derivative(function, center, n=i, order=d_pts) / math.factorial(i) coefficients.append(round(coeff, 5)) return coefficients # 正确调用:传入函数对象math.sin,而非math.sin(0)这类结果 print(findCoefficients(math.sin, 3, 0)) # 输出应为[1.0, 0.0, -0.16667]
内容的提问来源于stack exchange,提问作者matheus hopper
相关产品推荐
相关产品推荐

