如何将integrate.quad与数组一起使用

问题描述 投票:0回答:2

我想将Integrate.quad与数组一起使用,但它返回我:“TypeError:只有size-1数组可以转换为Python标量”

我知道所需的第一个参数必须是标量。但我想使用的参数来自一个依赖于一个参数并返回一个数组的函数,我无法解决问题:

这是我的 Python 脚本:

from scipy import integrate as intg

DfH_ref_jp = np.array([0,-393.52,-110.53,-74.87,-241.83,0]) *1000
n_jp = np.array([1.2,0.2,0.15,0.001,0.49,0.30])
Tref = 1298
Ta = 1310

def c_jp(T):
    t = T/1000
    XC = np.array([1,t,t**2,t**3,t**(-2)])
    Mah = M_ah(T)                            # a matrix defined before
    c = np.dot(Mah[:,:5],XC)

    return c

H1_jp = n_jp * (DfH_ref_jp + intg.quad(c_jp,Tref,Ta)[0])   # this where it doesn't work / [0] because intg.quad returns an array and I want the first value

所以我尝试了一个返回标量的函数:

def c_jp0(T):
    t = T/1000
    XC = np.array([1,t,t**2,t**3,t**(-2)])
    Mah = M_ah(T)
    c = np.dot(Mah[0,:5],XC)

    return c

H1_jp = np.zeros(6, dtype=float)
H1_jp[0] = n_jp[0] * (DfH_ref_jp[0] + intg.quad(c_jp0,Tref,Ta)[0]) 

它可以工作,但我不想指定 6 个函数:c_jp0 ... c_jp6。 有谁知道该怎么做吗? 谢谢

python function scipy numerical-integration
2个回答

0
投票

quad 方法旨在仅对一个标量变量积分标量函数。

如果您的积分只有一个积分变量,但取决于其他参数,您可以通过

quad(func, a, b, params)
中的参数传递它们。

如果你想对多个变量进行积分,你可以使用nquad,在这种情况下你必须为每个变量给出一个限制。

如果限制是常数,您可以直接传递它们,如果限制取决于其他积分变量,则必须将限制作为变量的函数传递 尚未集成。

例如 例如,计算一个角位于原点、另一个角位于点 (1,1,1) 的立方体的体积。

from scipy import integrate as intg
nquad(lambda x,y,z: 1.0, [(0,1), (0,1), (0,1)])

或者顶点为 (0,0,1)、(-1,-1,0) 和 (1,1,0) 的四棱锥的体积。其中

x
y
的限制取决于
z

from scipy import integrate as intg
intg.nquad(lambda x,y,z: 1.0, [lambda y,z: (z-1,1-z), lambda z: (z-1,1-z), (0,1)])
© www.soinside.com 2019 - 2024. All rights reserved.