We'll repeat the calculation from the previous example with NumPy. Execute the following code and see what happens:
import numpy as np def func(x): return np.exp(x) * np.cos(x) a=0; b=8 dx = 0.1 for i in range(4): x = np.arange(a, b + dx, dx) f = func(x) print("dx = {0} integral = {1}".format(dx, np.trapz(f,x))) dx = dx / 10
The output is shown in the following screenshot:
We defined a Python function that represents the mathematical function used in the previous example. We then used a for
loop to numerically integrate the function with trapz
, using different spacing of the independent variable x
. The first argument to trapz
is a NumPy array that contains the values of the function to be integrated. The x
values can be specified as either an array of values (which do not have to be uniformly spaced) or a single scalar value dx
that defines the spacing between points. If the array containing the...