Python 中的积分:添加不可调用的对象 [英] Integrals in Python: Add object not callable
本文介绍了Python 中的积分:添加不可调用的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用梯形规则求解 sin(x) 函数的泰勒近似的积分.代码看起来不错,但它一直给我以下错误:TypeError: 'Add' object is not callable"
I'm trying to solve an integral of a taylor approximation of a sin(x) function by using the trapezoid rule. The code seems fine but it keep giving me the following error: "TypeError: 'Add' object is not callable"
这是我的代码:
import math
import numpy
import sympy as sy
import numpy as np
from sympy.functions import sin,cos
import matplotlib.pyplot as plt
x = sy.Symbol('x')
f = sin(x)
# Factorial function
if n <= 0:
return 1
else:
return n*factorial(n-1)
taylor_series = sin(x).series(n=None)
# Do a trapezoid integration
xedge = numpy.linspace(a,b,N+1)
integral = 0.0
n = 0
while n < N:
integral += 0.5*(xedge[n+1] - xedge[n])*(f(xedge[n]) + f(xedge[n+1]))
n += 1
return integral
N = 3
a = 0.0
b = 1.0
z = sum([next(taylor_series) for i in range(N)])
print("Taylor series:",z)
# Trapezoid rule result
N = 2
while (N <= 2):
dd = trap(a,b,z,N)
print ('Trapezoid rule result:', dd)
N *= 2
回溯:
Error: Traceback (most recent call last):
File "Question1.py", line 86, in <module>
dd = trap(a,b,z,N)
File "Question1.py", line 67, in trap
integral += 0.5*(xedge[n+1] - xedge[n])*(f(xedge[n]) + f(xedge[n+1]))
TypeError: 'Add' object is not callable
推荐答案
在你的情况下 f
是一个 sympy
表达式.你不能仅仅通过调用它来评估它;你必须使用 evalf()
方法:
In your case f
is a sympy
expression. You cannot just evaluate it by calling it; you have to use the evalf()
method:
...
integral += 0.5*(xedge[n+1] - xedge[n])*(f.evalf(xedge[n]) + f.evalf(xedge[n+1]))
...
产生输出:
Taylor series: x**5/120 - x**3/6 + x
Trapezoid rule result: 0.0079345703125*x**5 - 0.158203125*x**3 + 1.0*x
End
这篇关于Python 中的积分:添加不可调用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文