Example of mean-value calculation using a straight Monte Carlo method

(* Setup *)
ntot=1000;
Array[x,ntot];
rho[x_]:=3x^2;

(* Calculation *)
i=0;
xsum=0.0;
While[i≤ntot,
x[i]=Random[];y=3*Random[];If[y<rho[x[i]],{xsum=xsum+x[i],i=i+1}]];
xavg=xsum/ntot

ListPlot[Array[x,ntot]]

Example of mean-value calculation using the Metropolis algorithm

(* Setup *)
ntot=100000;
step=0.01;
rho[x_]:=3x^2;

(* Calculation *)
i=0;
x[0]=0.1;
xsum=0.0;
While[i≤ntot,
delta=Random[]-0.5;side=delta/Abs[delta];xnew=x[i]+side*step;
If[xnew≤0,xnew=xnew+1];
If[xnew>1,xnew=xnew-1];
If[Random[]<rho[xnew]/rho[x[i]],{i=i+1,x[i]=xnew,xsum=xsum+x[i]}]];
xavg=xsum/ntot

ListPlot[Array[x,ntot],PlotRange->{0,1}]