I need to find the center of mass of a bar of length 12 using basic Monte Carlo integration. The mass distribution $ m(x) = .06x^2-3x+36$ and the definition of the center of mass is
$x_{com} = \frac{\int_0^{12}xm(x)dx}{\int_0^{12}m(x)dx}$
Therefore, in the Wolfram Language(non Monte Carlo) we have
m[x_]:=.06x^2-3x+36
Integrate[x m[x],{x,0,12}]/Integrate[m[x],{x,0,12}]
= 4.68966
The Monte Carlo Method employs the fact that $\lim_{n\rightarrow\infty}\frac{1}{n}\left(\sum_{i=1}^nf(x_i)\right) = $ The average of the function on the domain $[a,b]$ where $x_i$ is a uniformly distributed random real such that $a<x_i<b$.
$f_{avg} = \frac{1}{b-a}\int_a^bf(x)dx$ and so we can draw the following conclusion:
$\int_a^bf(x)dx\approx\frac{b-a}{n}\left(\sum_{i=1}^nf(x_i)\right) $
Therefore, I write
n=100000;
a=0;
b=12;
xi:=RandomReal[{a,b}]
mcNumerator = (1/n)Sum[xi m[xi],{i,1,n}];
mcDenominator = (1/n)Sum[m[xi],{i,1,n}];
MC = mcNUmerator/mcDenominator
The output of this little program converges to something near 6 for large $n$. What am I missing here?
Edit I see a potential problem in the mcNumerator where each of those $x_i$ are different.
xi
generates a new random number everytime it appears. Soxi m[xi]
actually generates two random numbers. But Monte-Carlo integrationswants to have the same random number both times. Also, you need the factor1/n
in both the numerator and denominator, no? $\endgroup$Method -> "MonteCarlo"
option onNIntegrate
? $\endgroup$