Trapezoidal Method Python Program

This program implements Trapezoidal Rule to find approximated value of numerical integration in python programming language.

In this python program, lower_limit and upper_limit are lower and upper limit of integration, sub_interval is number of sub interval and function f(x) to be integrated by Trapezoidal method is defined using python function definition def f(x):.

Python Source Code: Trapezoidal Rule


# Trapezoidal Method

# Define function to integrate
def f(x):
    return 1/(1 + x**2)

# Implementing trapezoidal method
def trapezoidal(x0,xn,n):
    # calculating step size
    h = (xn - x0) / n
    
    # Finding sum 
    integration = f(x0) + f(xn)
    
    for i in range(1,n):
        k = x0 + i*h
        integration = integration + 2 * f(k)
    
    # Finding final integration value
    integration = integration * h/2
    
    return integration
    
# Input section
lower_limit = float(input("Enter lower limit of integration: "))
upper_limit = float(input("Enter upper limit of integration: "))
sub_interval = int(input("Enter number of sub intervals: "))

# Call trapezoidal() method and get result
result = trapezoidal(lower_limit, upper_limit, sub_interval)
print("Integration result by Trapezoidal method is: %0.6f" % (result) )

Output

Output of above Trapezoidal method Python program is:

Enter lower limit of integration: 0
Enter upper limit of integration: 1
Enter number of sub intervals: 6
Integration result by Trapezoidal method is: 0.784241