Responsive Navbar with Google Search
☰ Menu
Home
Python
LaTeX
GNUPlot
Arduino
Feedback
Contact Us
Numerical Integration: Simpson’s 1/3rd Rule
Numerical Integration
Trapezoidal Method
Simpson’s 1/3rd Rule
Gaussian Quadrature method
Convolution of two Gaussian Functions
Simpson’s 1/3rd Rule: Program 1
Integration by Simpson method
def f(x): y=8*x**3+6*x**2+2*x+1 return y ll = 1 ul = 5 n=1000 #number of intervals h=float(ul-ll)/n s1=f(ll)+f(ul) d=4 s2=0 for i in range(1,n): x=ll+i*h s2=s2+d*f(x) d=6-d I=h/3.0*(s1+s2) print ('the required integration is : ',I)
Run Code
Output 1
Simpson’s 1/3rd Rule: Program 2
Integration by Simpson method
# Simpson's 1/3 Rule # Define function to integrate def f(x): return 1/(1 + x**2) # Implementing Simpson's 1/3 def simpson13(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 if i%2 == 0: integration = integration + 2 * f(k) else: integration = integration + 4 * f(k) # Finding final integration value integration = integration * h/3 return integration # Input section lower_limit = 1 upper_limit = 5 sub_interval = 1000 # Call trapezoidal() method and get result result = simpson13(lower_limit, upper_limit, sub_interval) print("Integration result by Simpson's 1/3 method is: %0.6f" % (result) )
Run Code
Output 2
Simpson’s 1/3rd Rule: Program 3
Integration by Simpson method
import numpy as np def simpsons_1_3_rule(f, a, b, n): """ Approximate the integral of a function using Simpson's 1/3 rule. Parameters: f : function The function to integrate. a : float The lower bound of the integration interval. b : float The upper bound of the integration interval. n : int The number of subintervals to use (must be even). Returns: float The approximate value of the integral. """ # Ensure the number of subintervals is even if n % 2 != 0: raise ValueError("Number of subintervals must be even.") # Calculate the width of each subinterval h = (b - a) / n # Evaluate the function at the endpoints integral = f(a) + f(b) # Sum the function values at the odd and even indices for i in range(1, n, 2): integral += 4 * f(a + i * h) for i in range(2, n, 2): integral += 2 * f(a + i * h) # Multiply by the width of each subinterval and divide by 3 integral *= h / 3.0 return integral def f(x): return np.sin(x) # Example function: sine of x # Define the integration bounds and number of subintervals a = 0 # Lower bound b = np.pi # Upper bound n = 10 # Number of subintervals (must be even) # Calculate the integral result = simpsons_1_3_rule(f, a, b, n) print(f"Approximate integral: {result:.6f}")
Run Code
Output 3