Link Search Menu Expand Document (external link)

How to write and evaluate Riemann sums


In calculus, a definite integral $\int_a^b f(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:

Using SymPy, in Python

View this solution alone.

This answer assumes you have imported SymPy as follows.

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 $\int_a^b f(x)\;dx$ as follows.

\[\lim_{n\to\infty}\sum_{i=1}^n f(a+i\Delta x)\cdot\Delta x,\]

where $\Delta x$ is defined as $\frac{b-a}{n}$.

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.

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.

$\displaystyle \frac{a - b}{n}$

The input $a+i\Delta 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\Delta x)$ is the height of a rectangle whose right edge is at $a+i\Delta x$.

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.

$\displaystyle \sum_{i=1}^{n} \frac{\left(a - b\right) \left(a + \frac{i \left(a - b\right)}{n}\right)^{2}}{n}$

We can actually use that formula to estimate $\int_a^b f(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.

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

$\displaystyle - \frac{17}{25}$

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

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

$\displaystyle - \frac{2}{3}$

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Topics that include this task


This website does not yet contain a solution for this task in any of the following software packages.

  • R
  • Excel
  • Julia

If you can contribute a solution using any of these pieces of software, see our Contributing page for how to help extend this website.