Responsive Navbar with Google Search
☰ Menu
Home
Python
LaTeX
GNUPlot
Arduino
Feedback
Contact Us
Numerical Integration: Gaussian Quadrature method
Numerical Integration
Trapezoidal Method
Simpson’s 1/3rd Rule
Gaussian Quadrature method
Convolution of two Gaussian Functions
Gaussian Quadrature method: Program 1
\[ \int_0^{\frac{\pi}{2}} \sin(x) \, dx \]
import numpy as np from scipy.integrate import quad # Define the function to integrate def f(x): return np.sin(x) # Example function: sin(x) # Gaussian quadrature 2-point nodes and weights nodes = np.array([-1/np.sqrt(3), 1/np.sqrt(3)]) weights = np.array([1, 1]) # Change of variable for [a, b] integration def gaussian_quadrature(f, a, b): # Change of variables mid = (b + a) / 2 half_length = (b - a) / 2 integral = 0 for i in range(len(nodes)): x = mid + half_length * nodes[i] integral += weights[i] * f(x) integral *= half_length return integral # Define the limits of integration a = 0 # Lower limit b = np.pi / 2 # Upper limit # Perform Gaussian Quadrature integration result = gaussian_quadrature(f, a, b) res_quad = quad(f, a, b)[0] print(f"Integral of sin(x) from {a} to {b} is approximately {result:.4f}") print(f"\nIntegral of sin(x) from {a} to {b} from scipy quad is {res_quad:.4f}")
Run Code
Output 1