To evaluate an integral using trapezoids or Simpson's rule, we can use Mathematica's capabilities to our advantage. Suppose we want to integrate over the interval [1,4] using . First, we will use trapezoids. The semicolons at the end of the statements below just keep Mathematica from printing the results on the screen, and allow me to put more than one command in a single cell.
f(x)=
3
x
n=20
In[]:=
leftend=1;rightend=4;num=20;width=(rightend-leftend)/num;x[i_]:=leftend+i*width;f[x_]:=x^3;trapestimate=(Sum[2f[x[i]],{i,1,num-1}]+f[leftend]+f[rightend])(width/2)
Out[]=
20427
320
Let's look at a decimal.
In[]:=
N[trapestimate]
Out[]=
63.8344
What is the actual value?
In[]:=
Integrate[x^3,{x,1,4}]
Out[]=
255
4
N[%]
63.75
Now for Simpson's. I'll use a second sum to add in the additional terms.
In[]:=
leftend=1;rightend=4;num=20;width=(rightend-leftend)/num;x[i_]:=leftend+i*width;f[x_]:=x^3;simpestimate=(Sum[2f[x[i]],{i,1,num-1}]+Sum[2f[x[i]],{i,1,num-1,2}]+f[leftend]+f[rightend])(width/3)
Out[]=
255
4
Wow. An exact answer! How did that happen?
N[%]
63.75