Riemann Sums

Off[General::"spell1",NMaximize::"nrnum",Plot::"plnr",Graphics::"gptn"]

Riemann[fct_:x^2,a_:1,b_:3,r_:4,nMax_:5,end_:1]:=Module[{(*Δ,xi,t,HMax,HMin,s*)},

f[z_]:=fct/.x->z;

	Δ=((b-a)/nMax);
	xi=Table[a+i Δ,{i,0,nMax}];
	t=Delete[Flatten[Table[{i,i},{i,1,nMax+1}]],{{1},{-1}}];

(*For determining the window*)
	HMax=NMaximize[{f[x],a-2Δ≤x&&x≤b+2Δ},{x}][[1]];
	HMin=Min[0,NMinimize[{f[x],a≤x&&x≤b},{x}][[1]]];
	s=1.4HMin-0.4HMax;

Approx=N[Sum[Δ f[(1-end)xi[[t[[2j+1]]]]+end xi[[t[[2j+2]]]]],{j,0,nMax-1}]];
Print["The approximate area is: ",Approx];

Show[{Graphics[{

(*Vertical label*)
Line[{{a-Δ,0},{a-Δ,f[(1-end)xi[[r]]+end xi[[r+1]]]}}],{GrayLevel[0.9],Line[{{a-2 Δ,f[(1-end)xi[[r]]+end xi[[r+1]]]},{a,f[(1-end)xi[[r]]+end xi[[r+1]]]}}]},
{Dashing[{0.02,0.02}],Line[{{a,f[(1-end)xi[[r]]+end xi[[r+1]]]},{xi[[r+1]],f[(1-end)xi[[r]]+end xi[[r+1]]]}}]},

Text[f[(1-end)xi[[r]]+end xi[[r+1]]],{a-2Δ,((f[(1-end)xi[[r]]+end xi[[r+1]]])/2)}],

(*Horizontal label*)
Line[{{xi[[r]],s},{xi[[r+1]],s}}],{GrayLevel[0.9],Line[{{xi[[r]],0.75s},{xi[[r]],1.1s}}]},{GrayLevel[0.9],Line[{{xi[[r+1]],0.75s},{xi[[r+1]],1.1s}}]},
Text[Δ,{xi[[r]]+(Δ/2),1.4s}],

(*Rectangles - General*)
Table[{GrayLevel[.7],Line[{{xi[[t[[2j+1]]]],0},
{xi[[t[[2j+1]]]],f[(1-end)xi[[t[[2j+1]]]]+end xi[[t[[2j+2]]]]]},
{xi[[t[[2j+2]]]],f[(1-end)xi[[t[[2j+1]]]]+end xi[[t[[2j+2]]]]]},
{xi[[t[[2j+2]]]],0}}]},{j,0,nMax-1}],

(*Rectangles - rth Rectangle*)
Table[{Hue[Random[]],Rectangle[{xi[[t[[2j+1]]]],0},

{xi[[t[[2j+2]]]],f[(1-end)xi[[t[[2j+1]]]]+end xi[[t[[2j+2]]]]]}]},{j,r-1,r-1}],

(*dashed height inside rectangle*)
{Dashing[{0.02,0.02}],Line[{{(1-end)xi[[r]]+end xi[[r+1]],0},{(1-end)xi[[r]]+end xi[[r+1]],f[(1-end)xi[[r]]+end xi[[r+1]]]}}]} 

}], (*end of graphics*)

(*Function plot*)
Plot[f[x],{x,a-2Δ,b+2Δ}]

}, (*end of display inputs*)


(*Graphic options*)
Axes->True,AxesLabel->TraditionalForm/@{x,y},TextStyle->{FontFamily->"Times",FontSize->14},(*Ticks->{If[nMax≤10,xi,False],False},*)PlotRange->All,ImageSize->{400,Automatic},AspectRatio->1](*end of display together*)



];

Manipulate[Riemann[(x^2)-3x,a,a+d,r,n,e],{{a,-1},0,5,1},{{d,6},1,5,1},{{r,1},1,n,1},{{n,4},1,20,1},{e,0,0}]