Numerical Integration with Mathematica

In this notebook, I'll show you how to use Mathematica to perform numerical integration using the five methods we've discussed in class. For these examples, we'll use main integral from class, namely Integrate[Exp[-x^2],{x,0,2}]. We can find a highly accurate approximation (to 10 digits in this case), using fancy Mathematica functions, like so:
In[]:=
N[Integrate[Exp[-x^2],{x,0,2}],10]
Out[]=
0.8820813908
In[]:=
b=2;​​a=0;​​f[x_]=Exp[-x^2];

Left Hand Rule

In[]:=
n=4.;​​Dx=(b-a)/n;​​LHR=Dx*Sum[f[a+k*Dx],{k,0,n-1}]​​
Out[]=
1.12604

Right Hand Rule

In[]:=
n=4.;​​Dx=(b-a)/n;​​RHR=Dx*Sum[f[a+k*Dx],{k,1,n}]
Out[]=
0.635198

Midpoint Rule

In[]:=
n=2.;​​Dx=(b-a)/n;​​MPR=Dx*Sum[f[a+(2k-1)Dx/2],{k,1,n}]
Out[]=
0.8842

Trapezoid Rule

In[]:=
n=2.;​​Dx=(b-a)/n;​​TPR=Dx*Sum[(f[a+k*Dx]+f[a+(k+1)*Dx])/2,{k,0,n-1}]
Out[]=
0.877037

Simpson's Rule

In[]:=
n=4.;(*nmustbeeven!!*)​​Dx=(b-a)/n;​​SPR=Dx/3*Sum[(f[a+2k*Dx]+4f[a+(2k+1)*Dx]+1f[a+(2k+2)*Dx]),{k,0,n/2-1}]​​TPR/3+2*MPR/3
Note: Simpson's Rule with n=4 is the same as the weighted average of 1/3Trapezoid + 2/3Midpoint. But the Trapezoid and Midpoint rule use n=2 (half of four).
Out[]=
0.881812
Out[]=
0.881812