# Simpson's 1/3 Rule implementation in Python
import numpy as np
def simpsons_one_third_rule(func, a, b, n):
"""
Approximate the integral of a function using Simpson's 1/3 Rule.
Parameters:
func (function): The function to integrate.
a (float): The lower limit of integration.
b (float): The upper limit of integration.
n (int): The number of sub-intervals (must be even).
Returns:
float: Approximation of the integral.
"""
# Check if n is even
if n % 2 != 0:
raise ValueError("Number of sub-intervals (n) must be even.")
h = (b - a) / n # Step size
x = np.linspace(a, b, n + 1) # Generate x values
y = func(x) # Evaluate the function at x values
# Apply Simpson's 1/3 Rule
integral = y[0] + y[-1] # First and last terms
integral += 4 * sum(y[1:n:2]) # Odd terms
integral += 2 * sum(y[2:n-1:2]) # Even terms
return (h / 3) * integral
# Example usage
if __name__ == "__main__":
# Define the function to integrate
def f(x):
return np.sin(x) # Example: Integrating sin(x)
# Define limits and number of intervals
a = 0 # Lower limit
b = np.pi # Upper limit
n = 6 # Number of sub-intervals (must be even)
# Perform integration
try:
result = simpsons_one_third_rule(f, a, b, n)
print(f"The approximate value of the integral is: {result}")
except ValueError as e:
print(e)