How to write and evaluate Riemann sums (in Python, using SymPy)
Task
In calculus, a definite integral
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
where
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
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
The input
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.
We can actually use that formula to estimate
1
total.subs( a, 1 ).subs( b, 3 ).subs( n, 10 ).doit()
We can also use a Riemann sum to get the exact area by taking a limit as
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
Content last modified on 24 July 2023.
See a problem? Tell us or edit the source.
Contributed by Nathan Carter (ncarter@bentley.edu)