Link Search Menu Expand Document (external link)

How to write and evaluate Riemann sums (in Python, using SymPy)

See all solutions.

Task

In calculus, a definite integral abf(x)dx can be approximated by a “Reimann sum,” which adds the areas of n rectangles that sit under the curve f. How can we write a Reimann sum using software?

Related tasks:

Solution

This answer assumes you have imported SymPy as follows.

1
2
from sympy import *                   # load all math functions
init_printing( use_latex='mathjax' )  # use pretty math output

In mathematics, we would write a Riemann sum approximating abf(x)dx as follows.

limni=1nf(a+iΔx)Δx,

where Δx is defined as ban.

This is easiest to understand if we break the Python code for it into several smaller parts. First, let’s choose a formula we will use as f(x) and the interval [a,b] in question.

1
2
3
4
var( 'x a b i n' )     # We need all these variables, as you can see above.
formula = x**2         # Let's pick f(x)=x^2 as a simple example.
delta_x = (a - b) / n  # Define delta x.
delta_x

abn

The input a+iΔx (which we will substitute into our formula f(x)) varies along the x axis between a and b as i counts from 1 to n. Each f(a+iΔx) is the height of a rectangle whose right edge is at a+iΔx.

1
2
3
4
5
input  = a + i*delta_x             # Input i to substitute into f(x)
height = formula.subs( x, input )  # Height of rectangle i
area   = delta_x * height          # Area of rectangle i
total  = Sum( area, (i,1,n) )      # Total area of all rectangles,
total                              # which is the Reimann sum.

i=1n(ab)(a+i(ab)n)2n

We can actually use that formula to estimate abf(x)dx if we substitute in actual values for a, b, and n. Let’s estimate the area from a=1 to b=3 with n=10 rectangles. Recall techniques for evaluating summations discussed in how to define a mathematical series.

1
total.subs( a, 1 ).subs( b, 3 ).subs( n, 10 ).doit()

1725

We can also use a Riemann sum to get the exact area by taking a limit as n.

1
2
3
Reimann_sum = total.subs( a, 1 ).subs( b, 3 )   # leave n as a variable
Reimann_sum = Reimann_sum.doit()                # simplify the summation
limit( Reimann_sum, n, oo )                     # take a limit as n -> infinity

23

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)