Math Maniac's Musings

Riemann sums in Python

In [1]:
import numpy as np
In [2]:
def f(x):
    return 3*x**2 - 2

interval = np.arange(1, 4, 0.5)
print(interval)
[ 1.   1.5  2.   2.5  3.   3.5]

We imported "numpy" (a numerical python package) to have access to a lot of useful methods (functions). In particular, I want the arange method which will create a partition of an interval $[a, b]$ into equally spaced subintervals.

I defined a function $f(x) = 3x^2 - 2$. Notice the use of the double asterix for exponentiation.

I used this method "arange" to create an interval which I called "interval". Note that by default "arange" creates a partition of left endpoints of subintervals. One of the nice things about these arrays of numbers is that we can apply functions to them as a whole as the examples below illustrate.

In [3]:
print(interval + 0.5) # Add 0.5 to each element of the array
[ 1.5  2.   2.5  3.   3.5  4. ]

In [4]:
print(interval * 2) # Multiply each element of the array by 2
[ 2.  3.  4.  5.  6.  7.]

In [5]:
print(interval**2) # Square each element of the array
[  1.     2.25   4.     6.25   9.    12.25]

In [6]:
print(f(interval)) # Apply the function f to each element of the array
[  1.     4.75  10.    16.75  25.    34.75]

We can sum all the elements of an array with the "sum" function as shown below.

In [7]:
print(sum(f(interval))) # Riemann sum
92.25

In []: