(** ROMBERG  **)

f[x_]:=Exp[x];
a=0.; b=1.;
true1=Integrate[f[x],x];
true=Integrate[f[x],{x,0,b}]//N

nmax=5;
h[1]=b-a;
r[1][1]=0.5*h[1]*(f[a]+f[b]);
Do[n=2^(k-1);h[k]=0.5*h[k-1];
sum=0.0;Do[sum+=f[a+j*h[k]],{j,1,n,2}];
r[k][1]=0.5*r[k-1][1]+h[k]*sum;
Do[r[k][j]=r[k][j-1]+(r[k][j-1]-r[k-1][j-1])/(4^(j-1)-1),{j,2,k}],{k,2,nmax}]
Do[err=Abs[r[n][n]-true];Print["n = ", n, "    err = ",err],{n,1,nmax}]
Do[Print["n = ",n,"  j = ", j,"  r = ", r[n][j]],{n,1,nmax},{j,1,n}]

nmax=5;tol=1.0*10^(-6);
h[1]=b-a;
r[1][1]=0.5*h[1]*(f[a]+f[b]);

k=2;test=1.0;
While[test>tol,n=2^(k-1);h[k]=0.5*h[k-1];
sum=0.0;Do[sum+=f[a+j*h[k]],{j,1,n,2}];
r[k][1]=0.5*r[k-1][1]+h[k]*sum;
Do[r[k][j]=r[k][j-1]+(r[k][j-1]-r[k-1][j-1])/(4^(j-1)-1),{j,2,k}];test=Abs[r[k][k]-r[k-1][k-1]];test1=Abs[r[k][k]-true];Print["k = ", k, "   test = ",test, "   test1 = ",test1];k++]

(* SECONDA FUNZIONE *)

f[x_]:=x*Sin[x];
a=0.; b=2.*Pi;
Plot[f[x],{x,0,b}]
true1=Integrate[f[x],x];
true=Integrate[f[x],{x,a,b}]//N

nmax=10;
h[1]=b-a;
r[1][1]=0.5*h[1]*(f[a]+f[b]);
Do[n=2^(k-1);h[k]=0.5*h[k-1];
sum=0.0;Do[sum+=f[a+j*h[k]],{j,1,n,2}];
r[k][1]=0.5*r[k-1][1]+h[k]*sum;
Do[r[k][j]=r[k][j-1]+(r[k][j-1]-r[k-1][j-1])/(4^(j-1)-1),{j,2,k}],{k,2,nmax}]
Do[err=Abs[r[n][n]-true];Print["n = ", n, "    err = ",err],{n,1,nmax}]

(* Do[Print["n = ",n,"  j = ", j,"  r = ", r[n][j]],{n,1,nmax},{j,1,n}];*)

nmax=5;tol=1.0*10^(-6);
h[1]=b-a;
r[1][1]=0.5*h[1]*(f[a]+f[b]);

k=2;test=1.0;
While[test>tol,n=2^(k-1);h[k]=0.5*h[k-1];
sum=0.0;Do[sum+=f[a+j*h[k]],{j,1,n,2}];
r[k][1]=0.5*r[k-1][1]+h[k]*sum;
Do[r[k][j]=r[k][j-1]+(r[k][j-1]-r[k-1][j-1])/(4^(j-1)-1),{j,2,k}];test=Abs[r[k][k]-r[k-1][k-1]];test1=Abs[r[k][k]-true];Print["k = ", k, "   test = ",test, "   test1 = ",test1];k++]

Do[n=2^(k-1);h[k]=0.5*h[k-1];
sum=0.0;Do[sum+=f[a+j*h[k]],{j,1,n,2}];
r[k][1]=0.5*r[k-1][1]+h[k]*sum;
Do[r[k][j]=r[k][j-1]+(r[k][j-1]-r[k-1][j-1])/(4^(j-1)-1),{j,2,k}],{k,2,nmax}]
Do[err=Abs[r[n][n]-true];Print["n = ", n, "    err = ",err],{n,1,nmax}]
Do[Print["n = ",n,"  j = ", j,"  r = ", r[n][j]],{n,1,nmax},{j,1,n}]