Approximating Definite Integrals with Riemann Sums
In this example, we demonstrate how to approximate a definite integral using a Left-Endpoint Riemann Sum. We would like to approximate the area under the graph of y=e^(-x^2) from x=0 to x=2 using 50 rectangles. We begin by importing our sympy package as usual, but we have one more package to use. Since this is a numerical approximation, we will use several commands from the numpy package, so we will use a shorthand notation for it, calling it np. This means whenever we want to use a numeric command, we will put the “np.” in front of it so Python knows we are using the numeric command. We do this because there are some commands in both packages with the same name that do different things. Next, we define x as a symbolic variable, and define our expression, calling it f. Recall our process: the steps for approximating an integral by hand are:
1) Define dx = (b-a)/n
2) Create a list of x-values from x=a to x=b-dx since we want left endpoints
3) Find the corresponding y-values
4) Sum these y-values and multiply by dx
In our example, a=0, b=2, and n=50. We will call our list of x-values xi. Since the values are equally spaced, we can easily create the list using the arange command in numpy. A quick check on help documentation shows us that the options for the arange command are the first value, a, one BEYOND our last value, b, and our stepsize, dx. Like the range command, our arange command creates a list from a INCLUSIVE to b EXCLUSIVE with stepsize dx. For step 3, we use list comprehension to create the list of y-values all at once. Finally, step 4 requires the sum command, another command in the numpy package. Don’t forget to multiply by dx as well! Now we can print our result with appropriate explanation.