Search code examples
pythonscipyacoustics

How to integrate a complex (not in the real vs complex definition) function


I have this monster expression for the pressure distribution around a sphere, the expression being equation where Re[A] is the real component of a predefined coefficient, P are the legendre polynomials, and j and n are spherical Bessel and Neumann functions. I wish to integrate this over theta, so I defined a function for the equation above as follows

def P_rms_calc(k,a,n_max,theta): # Return the P_rms function

# Obtain Coefficients
A_m = A_m_coeff(k,a,P_a,l,z0,n_max)

P_t = []
for m in range(n_max):
    for l in range(m+1):
        P_t.append(0.5*numpy.real(A_m[l])*numpy.real(A_m[m-l])*(legendre(l)(numpy.cos(theta)))*(legendre(m-l)(numpy.cos(theta)))*((spherical_jn(l,k*r)*spherical_jn(m-l,k*r))+
                                                                                                                            (spherical_yn(l,k*r)*spherical_yn(m-l,k*r))))
    P_rms = numpy.sqrt(sum(P_t))
return P_rms

However, when I try to integrate using scipy.integrate.quad like so,

a0, err = quad(P_rms_calc(k,a,n_max,theta),-numpy.pi,numpy.pi)

it gives 'error: quad: first argument is not callable'. And if I don't give the arguments of the function like so,

a0, err = (1/(2*numpy.pi))*quad(P_rms_calc,-numpy.pi,numpy.pi)

it gives 'TypeError: P_rms_calc() takes exactly 8 arguments (1 given)'

Am I missing something simple in the use of the integration tool quad? If not is there any better way to try and integrate this expression? Feel free to also recommend a more efficient way to define the rms pressure expression. For reference, I'm only summing from m=0 to 6 or so, so computation time isn't terrible using the for loops.Thanks for the help!


Solution

  • Use args argument to pass through extra arguments of the integrand:

    >>> def func(x, a, b):
    ...    return a * x**b 
    ... 
    >>> quad(func, 0, 1, args=(1., 2.))
    (0.33333333333333337, 3.700743415417189e-15)