from __future__ import print_function import numpy as np from scipy.integrate import simps from numpy import trapz # The y values. A numpy array is used here, # but a python list could also be used. y = np.array([5, 20, 4, 18, 19, 18, 7, 4]) # Compute the area using the composite trapezoidal rule. area = trapz(y, dx=5) print("area =", area) # Compute the area using the composite Simpson's rule. area = simps(y, dx=5) print("area =", area)
Here is what the above code is Doing:
1. The y values are the heights of the bars in the bar chart.
2. The x values are the left edges of the bars.
3. The width of each bar is 5.
4. The area of each bar is the height times the width.
5. The area of the whole bar chart is the sum of the areas of the bars.
6. The area of the bar chart is the integral of the function that is
zero everywhere except for the top of each bar.
7. The composite trapezoidal rule approximates the integral by
dividing the bar chart into trapezoids and adding up the areas
of the trapezoids.
8. The composite Simpson’s rule approximates the integral by
dividing the bar chart into parabolas and adding up the areas
of the parabolas.