直接上 mathematica代码
"Monte Carlo积分法(蒙特卡罗积分法)"
monteCarlo[f_, indvar_, m_, a_, b_, n_] :=
Module[{
g, x, xr, yr, area, lim, areaave, y1, y2},
g = f /. indvar -> x;
lim = Length[n];
area = Table[0, {
k, 1, lim}];
For[k = 1, k <= lim, k++,
For[couter = 0; i = 1, i <= n[[k]], i++,
xr = a + (b - a)*RandomReal[];
yr = m*RandomReal[];
If[yr <= g /. x -> xr, couter += 1;];
area[[k]] = m*(b - a)*couter/n[[k]]]];
areaave =
Sum[n[[i]]*area[[i]], {
i, 1, lim}]/Sum[n[[i]], {
i, 1, lim}];
y1 = Integrate[g, {
x, a, b}] // N;
(*y2=Integrate[g,{
x,a,b}];*)
data = {
{
HoldForm[\!\(
\*SubsuperscriptBox[\(\[Integral]\), \(a\), \(b\)]\(f \
\[DifferentialD]indvar\)\)]}, Join[{
"PointNum"}, n],
Join[{
"Approx"}, area],
Join[{
"Err"}, area - y1], {
"AreaAverage", areaave}, {
"Integrate",
y1}};
Grid[data,
Background -> {
None, {
Lighter[Orange, .9], {
White,
Lighter[Blend[{
Blue, Green}], .8]}}},
Dividers -> {
{
Darker[Gray, .6], {
Lighter[Gray, .5]},
Darker[Gray, .6]}, {
Darker[Gray, .6], Darker[Gray, .6], {
False},
Darker[Gray, .6]}}, Alignment -> Center,
Frame -> Darker[Gray, .6]]
]
Pnumber = Table[k*10^2, {
k, 1, 15, 2}];
monteCarlo[z*Sqrt[1 - z], z, 0.5, 0, 1, Pnumber]
monteCarlo[x*E^(-2 x^2), x, 0.5, 0, 1, Pnumber]
monteCarlo[Sin[y] E^Cos[y], y, 0.5, \[Pi]/2, \[Pi], Pnumber]
monteCarlo[2 x*ArcSin[x^2], x, 0.5, 0, 1/Sqrt[2], Pnumber]