I was doing a numerical integration where instead of using
scipy.integrate.dblquad
I tried to build the double integral directly using
scipy.integrate.quad
From camz's answer: https://stackoverflow.com/a/30786163/11141816
a=1
b=2
def integrand(theta, t):
return sin(t)*sin(theta);
def theta_integral(t):
# Note scipy will pass args as the second argument
return integrate.quad(integrand, b-a, t , args=(t))[0]
integrate.quad(theta_integral, b-a,b+a )
However, the part where it was confusing was how the args was passed through the function. For example, in the post args=(t)
was pass through to the second argument t
of the function integrand automatically, not the first argument theta
, where in the scipy document https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html the only reference was
args: tuple, optional
Extra arguments to pass to func.
and in fact their arguments had a comma ,
to be args=(1,)
, instead of args=(1)
directly.
What if I decide to pass several variables, i.e.
def integrand(theta, t,a,b):
return sin(t)*sin(theta)*a*b;
how would I know which args(t,a,b)
or args(t,a,b,)
were the correct args()
for the function?
How to pass args()
to integrate.quad in scipy?
1条答案
按热度按时间z2acfund1#
一个简单的例子。我没有使用
args
,只是展示它们:这就是
args
的全部内容。看一下
quad
的代码,第一行是所以如果你使用
args=(t)
,它将被修改为args=(t,)
。记住,在python中(2)
和2
是一样的;这个()函数只对复杂情况下的操作进行分组,否则它们将被忽略。但是(1,)
是一个元组,如(1,2)
。实际上是逗号定义了元组。用你内在的功能,加上一个打印:
t
是一个数组,np.sin(t)
也是一个数组,返回值也是一个数组。但是你没有传递数组。通过quad调用它,theta
会变化,t
不会:实际的错误是在编译的代码中引发的,所以并不完全透明,但效果与我试图传递3个参数相同: