def simpson_13(f, a, b, n): """ Approximates the definite integral of f(x) from a to b using Simpson's 1/3 Rule. Parameters: f : function - The mathematical function to integrate a : float - Lower limit of integration b : float - Upper limit of integration n : int - Number of subintervals (Must be an even integer) """ if n % 2 != 0: raise ValueError("The number of subintervals (n) must be even.") # Calculate step size h = (b - a) / n # Initialize the sum with boundary terms integral = f(a) + f(b) # Add weighted internal points for i in range(1, n): x = a + i * h if i % 2 == 0: integral += 2 * f(x) # Even indices multiplied by 2 else: integral += 4 * f(x) # Odd indices multiplied by 4 # Multiply by final scaling factor return integral * (h / 3) # --- Example Usage --- if __name__ == "__main__": # Define an example function: f(x) = x^2 def my_function(x): return x**2 lower_limit = 0 upper_limit = 3 intervals = 6 # Must be even result = simpson_13(my_function, lower_limit, upper_limit, intervals) print(f"Approximated Integral: {result:.6f}") # Analytical solution for x^2 from 0 to 3 is (3^3)/3 = 9.0