我有点卡在一个函数上,我试图通过scipy,python进行数字整合。
为简单起见,我将函数定义为:
integral f(x,y)= SUM[double integral(ax+by)dxdy]
a
和b
是常量,但它们对于每个积分的方程都不同。我已经分别集成了每个函数,然后将结果汇总到所有积分上,但是这需要很长的时间来计算,并且它不适合我试图实现的目标。
有没有办法通过扩展总和来一次整合整个功能:
integral f(x,y)=double integral [(a1x+b1y)+(a2x+b2y)...(anx+bny)]dxdy
然后将带有(a,b)
元组列表等的函数传递给scipy的dblquad函数?
目前我正在努力寻找与此相关的任何文献中的任何内容。
*编辑
我已经提供了一个示例代码来展示我想要更清楚地实现它的目的:
import sys
import re
import math
from scipy.integrate import dblquad
def f((x,y),variables):
V=0
for v in variables:
a,b=v
V=V+ax+by
return (V)
def integral(x_max,y_max,variables):
return dblquad(f, 0, y_max, lambda x: 0, lambda x: x_max,args=variables)
def main():
variables=[(1,2),(3,4),(5,6)] #example variables. The length of this list can change with the code I am running.
x_max=y_max=1
integral(x_max,y_max,variables)
if __name__ == '__main__':
main()
返回的错误是:
Traceback (most recent call last):
File "integration_example.py", line 23, in <module>
main()
File "integration_example.py", line 19, in main
integral(x_max,y_max,variables)
File "integration_example.py", line 14, in integral
return dblquad(f, 0, y_max, lambda x: 0, lambda x: x_max,args=variables)
File "/usr/lib/python2.7/dist-packages/scipy/integrate/quadpack.py", line 435, in dblquad
return quad(_infunc,a,b,(func,gfun,hfun,args),epsabs=epsabs,epsrel=epsrel)
File "/usr/lib/python2.7/dist-packages/scipy/integrate/quadpack.py", line 254, in quad
retval = _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points)
File "/usr/lib/python2.7/dist-packages/scipy/integrate/quadpack.py", line 319, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
File "/usr/lib/python2.7/dist-packages/scipy/integrate/quadpack.py", line 382, in _infunc
myargs = (x,) + more_args
TypeError: can only concatenate tuple (not "list") to tuple
显然,函数不喜欢我传递一个值列表,以我写这个的方式放入积分。有没有办法做到这一点? (对不起,这可能是一个更好的方法来表达问题)。
答案 0 :(得分:0)
我不完全确定,但似乎你的错误基本上只是指你将args
传递给f
的论点为variables
(其中也应该是tuple
,而不是list
)。然后,您应unpack使用*args
{{3}}未知数量的变量。尝试:
import sys
import re
import math
from scipy.integrate import dblquad
def f(x,y,*args):
V=0
for v in args:
a,b=v
V=V+a*x+b*y
return (V)
def integral(x_max, y_max, variables):
return dblquad(f, 0, y_max, lambda x: 0, lambda x: x_max, args=variables)
def main():
variables=((1,2),(3,4),(5,6)) #example variables. The length of this list can change with the code I am running.
x_max=y_max=1
integral(x_max,y_max,variables)
if __name__ == '__main__':
main()
(另请注意,您需要a*x
,而不是ax
。)