Search code examples
pythonintegral

How to numerically integrate f(x) between a lower and an upper bound?


I have been told to modify the code i had before to integrate between the lower bound a and upper bound b.This is done by adding another parameter, width. The integral can then be calculated by summing up lots of rectangles of with area (width*f(x)). An example of what I need to calculate is shown below

Calculate the integrals of f(x)=x from 0 to 100.

My code I have to modify is this, this is used to calculate product, how do I modify this to calculate integrals?

def product(f, a, b):
    total = 1
    for i in range(a, b+1):
        total *= f(i)
    return total

Solution

  • Edited:

    Assuming your function f(x) calculates the functional value at x, you can do something like this:

    def f(x): # define this according to your function.
        return x*x
    
    def integrate(func, a, b, width):
        total = 0
        i = a
        while i <= b:
            total += func(i)
            i += width
        return total * width
    
    width = 0.01
    integral = integrate(f, 0, 100, width)
    print(integral)
    

    Output:

    333283.3350000302
    

    True value of the integral is 333333.333333, so the result is quite accurate.

    Edit:

    To use some other functions like sin or cos, you can use built-in functions, inside the function f(x) like this:

    def f(x):
        return math.sin(x)
    

    Then to integrate from 0 to pi, use this:

    width = 0.01
    integral = integrate(f, 0, math.pi, width)
    print(integral)
    

    Remember to import math using import math.