python 中的函数与固定变量列表的数值二重积分

Numerical double integration of a function in python with a list of fixed variables

我对尝试通过 scipy、python.

进行数值积分的函数有点卡住了

为简单起见,我将函数定义为:

integral f(x,y)= SUM[double integral(ax+by)dxdy]

ab 是常数,但它们对于积分的每个方程都是不同的。我分别对每个函数进行了积分,然后将所有积分的结果相加,但是这需要花费大量时间来计算,而且对于我想要实现的目标来说并不理想。

有没有办法通过扩展总和来一次整合整个函数,使得:

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

显然,该函数不喜欢我以我编写的方式传递值列表以放入积分中。有没有办法做到这一点? (抱歉,这可能是表达问题的更好方式)。

我不完全确定,但看起来你的错误基本上只是因为你指的是你作为 args 传递给 f 的参数作为 variables (这也应该是 tuple,而不是 list)。然后你应该 unpack 未知数量的变量 *args。尝试:

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。)