fork download
  1. # Simpson's 1/3 Rule implementation in Python
  2. import numpy as np
  3.  
  4. def simpsons_one_third_rule(func, a, b, n):
  5. """
  6. Approximate the integral of a function using Simpson's 1/3 Rule.
  7.  
  8. Parameters:
  9. func (function): The function to integrate.
  10. a (float): The lower limit of integration.
  11. b (float): The upper limit of integration.
  12. n (int): The number of sub-intervals (must be even).
  13.  
  14. Returns:
  15. float: Approximation of the integral.
  16. """
  17. # Check if n is even
  18. if n % 2 != 0:
  19. raise ValueError("Number of sub-intervals (n) must be even.")
  20.  
  21. h = (b - a) / n # Step size
  22. x = np.linspace(a, b, n + 1) # Generate x values
  23. y = func(x) # Evaluate the function at x values
  24.  
  25. # Apply Simpson's 1/3 Rule
  26. integral = y[0] + y[-1] # First and last terms
  27. integral += 4 * sum(y[1:n:2]) # Odd terms
  28. integral += 2 * sum(y[2:n-1:2]) # Even terms
  29.  
  30. return (h / 3) * integral
  31.  
  32. # Example usage
  33. if __name__ == "__main__":
  34. # Define the function to integrate
  35. def f(x):
  36. return np.sin(x) # Example: Integrating sin(x)
  37.  
  38. # Define limits and number of intervals
  39. a = 0 # Lower limit
  40. b = np.pi # Upper limit
  41. n = 6 # Number of sub-intervals (must be even)
  42.  
  43. # Perform integration
  44. try:
  45. result = simpsons_one_third_rule(f, a, b, n)
  46. print(f"The approximate value of the integral is: {result}")
  47. except ValueError as e:
  48. print(e)
  49.  
Success #stdin #stdout 0.82s 41396KB
stdin
Standard input is empty
stdout
The approximate value of the integral is: 2.0008631896735367