(** FORMULE DI NEWTON-COTES COMPOSTE **)

f[x_]:=Exp[x];
a=0.; b=1.;
true1=Integrate[f[x],x];
true=Integrate[f[x],{x,0,1}]//N
x[0]=a;
n=20;
x[n]=b;
h=(b-a)/n;
Do[x[i+1]=x[i]+h,{i,0,n-2}];
sum=0.0;
Do[sum+=f[x[i]],{i,1,n-1}];
trap=0.5*h*(f[a]+2.0*sum+f[b])
err=Abs[trap-true]

w[0]=1.;w[n]=1.;
Do[w[i]=4.,{i,1,n-1,2}]
Do[w[i]=2.,{i,2,n-2,2}]
sum=0.0;
Do[sum+=w[i]*f[x[i]],{i,0,n}]
simps=h*sum/3.
err=Abs[simps-true]

ticks2={{0,0.05,0.1,0.15,0.2},{0.001,0.002,0.003,0.004,0.005}};
prange={{0,0.2},{0,0.005}};

nmax=200;
Do[x[n]=b;
h=(b-a)/n;hh[n]=h;
Do[x[i+1]=x[i]+h,{i,0,n-2}];
sum=0.0;
Do[sum+=f[x[i]],{i,1,n-1}];
trap=0.5*h*(f[a]+2.0*sum+f[b]);
errtrap[n]=Abs[trap-true];
w[0]=1.;w[n]=1.;
Do[w[i]=4.,{i,1,n-1,2}];
Do[w[i]=2.,{i,2,n-2,2}];
sum=0.0;
Do[sum+=w[i]*f[x[i]],{i,0,n}];
simps=h*sum/3.;
errsimps[n]=Abs[simps-true],{n,4,nmax,2}]
pl1=ListPlot[Table[{hh[n],errtrap[n]},{n,4,nmax,2}],PlotStyle->RGBColor[1,0,0],PlotRange->prange,Ticks->ticks2];
pl2=ListPlot[Table[{hh[n],1000.*errsimps[n]},{n,4,nmax,2}],PlotStyle->RGBColor[0,0,1],PlotRange->prange,Ticks->ticks2];
Show[pl1,pl2]

(* SECONDA FUNZIONE *)

f[x_]:=x*Sin[x];
Plot[f[x],{x,0,4.Pi}]

a=0.; b=4.*Pi;
true1=Integrate[f[x],x];
true=Integrate[f[x],{x,0,b}]//N

x[0]=a;
n=200;
x[n]=b;
h=(b-a)/n;
Do[x[i+1]=x[i]+h,{i,0,n-2}];
sum=0.0;
Do[sum+=f[x[i]],{i,1,n-1}];
trap=0.5*h*(f[a]+2.0*sum+f[b])
err=Abs[trap-true]

w[0]=1.;w[n]=1.;
Do[w[i]=4.,{i,1,n-1,2}]
Do[w[i]=2.,{i,2,n-2,2}]
sum=0.0;
Do[sum+=w[i]*f[x[i]],{i,0,n}]
simps=h*sum/3.
err=Abs[simps-true]

ticks2={{0,0.05,0.1,0.15,0.2},{0.01,0.02,0.03,0.04}};
prange={{0,0.15},{0,0.04}};
nmax=1000;
Do[x[n]=b;
h=(b-a)/n;hh[n]=h;
Do[x[i+1]=x[i]+h,{i,0,n-2}];
sum=0.0;
Do[sum+=f[x[i]],{i,1,n-1}];
trap=0.5*h*(f[a]+2.0*sum+f[b]);
errtrap[n]=Abs[trap-true];
w[0]=1.;w[n]=1.;
Do[w[i]=4.,{i,1,n-1,2}];
Do[w[i]=2.,{i,2,n-2,2}];
sum=0.0;
Do[sum+=w[i]*f[x[i]],{i,0,n}];
simps=h*sum/3.;
errsimps[n]=Abs[simps-true],{n,4,nmax,2}]
pl1=ListPlot[Table[{hh[n],errtrap[n]},{n,4,nmax,2}],PlotStyle->RGBColor[1,0,0],PlotRange->prange,Ticks->ticks2];
pl2=ListPlot[Table[{hh[n],1000.*errsimps[n]},{n,4,nmax,2}],PlotStyle->RGBColor[0,0,1],PlotRange->prange,Ticks->ticks2];
Show[pl1,pl2]