pythonarraysnumerical-integration

How to integrate a function for multiple upper limits using Python?


Suppose I have an integrand, and I want to integrate the function using various upper limits. In my code, I have the upper limit as 1. But I want to evaluate the integral using 1, 2, 4, 6. How do I do that? Do I use the map function? I've tried setting the upper limit as an array but I get all kinds of errors. This is my code using only 1. Any help is appreciated.

from scipy.integrate import quad
def integrand(x, a, b):
    return a*x**2 + b

a = 2
b = 1
I = quad(integrand, 0, 1, args=(a,b))

Solution

  • You can define a function to simply call quad with each of your desired upper bounds.

    from scipy.integrate import quad
    # typing is just for clarity
    from typing import List
    
    def integrand(x, a, b):
        return a*x**2 + b
    
    def multi_integrate(a,b,lb:float, ub_ls:List[float]) -> List:
        results = []
        # loop through all upper bounds
        for ub in ub_ls:
            results.append(quad(integrand,lb,ub,args=(a,b)))
        return results
    
    # variables
    a = 2
    b = 1
    # upper bound and list of lower bounds
    lb = 0
    ub_ls = [1,2,4,6]
    # get a list of your integral results
    I = multi_integrate(a,b, lb,ub_ls)
    

    I hope this is your intended functionality.