Search code examples
pythonfunctionscipynumerical-integration

How to use integrate.quad with an array


I would like to use integrate.quad with an array but it returns me : "TypeError: only size-1 arrays can be converted to Python scalars"

I understand that the first argument which is required must be a scalar. But the argument I want to use comes from a function that depends on one parameter and that return an array and I can't get the problem fixed:

Here is my script in 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

So I have tried with a function which returns a scalar:

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

It works but I don't want to specify 6 functions : c_jp0 ... c_jp6. Does anyone has an idea how to do it ? Thanks


Solution

  • You're looking for quad_vec: https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad_vec.html