Riemann Sums in Mathematica
David McClendon

Left-hand Riemann sums

This code computes left-hand Riemann sums and displays a picture of the rectangles whose area is added to compute the Riemann sum.  To use this code, all you have to do is change the first two lines as necessary:

In the first line, type the function whose Riemann sum you are computing, defining it as f(x) using the usual syntax with the underscore.  This line should end with a semicolon.

In the second line, define the partition P (end this line with a semicolon).  There are two ways to do this:
  1) Explicitly type in the elements of P, surrounding them with a set of braces.
        Example:  P = {0,2,5,6,8}
  2) If P is the partition of [a,b] into n equal length subintervals, use the Range command.  This command has three inputs:  a, b, and the width of each subinterval (which must be (b-a)/n).   
        Example:  P = Range[0,4,1/10] would define the partition of [0,4] into 40 equal length subintervals.

Leave the rest of the code alone (for an explanation of what exactly it does, consult Section A.5 of the appendix to my lecture notes and/or ask me).

When you execute the cell, you will get a picture of the graph of f with rectangles corresponding to the left-hand sum displayed.  The left-hand Riemann sum is computed and printed below the picture.

f[x_] =Cos[x] + 2;
P={0, 1,3,5,6,7};

ymin = Min[0,NMinimize[{f[x], P[[1]] < x && P[[Length[P]]] ≥ x}, x][[1]]];
ymax = Max[0,NMaximize[{f[x], P[[1]] < x && P[[Length[P]]] ≥ x},x][[1]]];
Show[DiscretePlot[f[x], {x,Drop[P,-1]}, ExtentSize -> Right, PlotRange -> {{P[[1]], P[[Length[P]]]}, {ymin,ymax}}],
Plot[{f[x]}, {x, P[[1]], P[[Length[P]]]}, PlotStyle -> {Red, Thick}, PlotRange -> {ymin, ymax}]]
Sum[N[f[P[[j]]]] (P[[j+1]] - P[[j]]), {j, 1, Length[P]-1}]

Right-hand Riemann sums

This code works the same way the above code works, except that it computes and displays a right-hand Riemann sum for the function f(x) with respect to the partition P.

f[x_] =x^3;
P=Range[0,5,1/2];

ymin = Min[0,NMinimize[{f[x], P[[1]] < x && P[[Length[P]]] ≥ x}, x][[1]]];
ymax = Max[0,NMaximize[{f[x], P[[1]] < x && P[[Length[P]]] ≥ x}, x][[1]]];
Show[DiscretePlot[f[x], {x,Drop[P,1]}, ExtentSize -> Left, PlotRange -> {{P[[1]], P[[Length[P]]]}, {ymin,ymax}}],
Plot[{f[x]}, {x, P[[1]], P[[Length[P]]]}, PlotStyle -> {Red, Thick}, PlotRange -> {ymin, ymax}]]
Sum[N[f[P[[j+1]]]] (P[[j+1]] - P[[j]]), {j, 1, Length[P]-1}]