Search code examples
pythonscipyintegral

Integrating a function which itself involves an integral using SciPy


So what I'm trying to do is calculate an integral over y, then I want to calculate exp(-t* the solution) and integrate that over x.

It's supposed to be like this:

Integral over x (exp(-t* B)) from 0 to Pi

B= Integral over y(3.0*(sin(x)*sin(y)*sin(TM)+cos(x)*cos(TM))**2.0-1.0)**2.0 from 0 to 2Pi

I tried to do it with scipy, but it won't do the integration over y without an x.

Here's my code so far:

from numpy import cos, sin, exp
import math
import scipy.integrate as integrate

t=0.0
TM=(54.74/180)*math.pi

def integrand(y,x):
    return (3.0*A(y,x)**2.0-1.0)**2.0

def A(y,x):
    return sin(x)*sin(y)*sin(TM)+cos(x)*cos(TM)

while t<10:
    t+=4
    resultbet, err=integrate.nquad(integrand, [(0.0, 2*math.pi)])
    result=exp(-t*resultbet)
    resultalph, err=integrate.nquad(result, [(0.0, math.pi)])

Solution

  • You want to integrate over y, then apply exponential function, then integrate over x. This is not a double integral, this is integration of a function defined in terms of an integral. I rewrote the code accordingly, keeping your definitions of A and integrand:

    def B(x):
        return integrate.quad(lambda y: integrand(y,x), 0, 2*math.pi)[0]
    
    while t<10:
        t += 4
        result = integrate.quad(lambda x: x*exp(-t*B(x)), 0, math.pi)
        print(result)
    

    Output:

    (0.28030701904213656, 1.0526577138223263e-08)
    (0.1972630762340601, 1.3996736645569703e-12)
    (0.16081518182419666, 9.188712047715815e-11)
    

    Here, first number is the value of integral, the second is an error estimate; this is what integrate.quad returns. (And this is why there is [0] at the end of function B.)

    The function B takes x as an argument and returns the result of one-dimensional integration over y from 0 to 2*pi. Then in a loop, the function x*exp(-t*B(x)) is integrated.