I wanted to implement the Monte Carlo method for multiple integrals approximation in Wolfram Mathematica. Namely I wanted to let the user insert as input the dimension of the integral and the number of samples to be considerated and then perform the method. I implemented the following code:
monteCarloIntegration[f_, a_, b_, n_, dim_] :=
Module[{randomNumbers, values, average, integrand},
randomNumbers = RandomReal[#, n] & /@ Transpose[{a, b}^dim];
integrand = Apply[f, randomNumbers, {1}];
values = Total[integrand];
average = Mean[values];
(b - a)^dim*average];
(Example for dim = 3 (triple integral)):
f[x_, y_, z_] := x^2 + y^2 + z^2;
a = {0, 0, 0};
b = {1, 1, 1};
n = 1000;
dim = 3;
trueV = (1/4) (Pi)^(3/2);
(*monteCarloIntegration[f,a,b,n,dim]*)
But when I plot the following:
errorValues = Table[Abs[trueV-monteCarloIntegration[f, a, b, i, dim]], {i, 1, 1000}];
ListLinePlot[errorValues,
PlotLabel -> "Error between the approximation and the real value",
AxesLabel -> {"Number of Samples", "Error"}]
the graphic is displayed (I mean the axis and the label) but it's an empty plot. Could someone hlep me to fix this? Thank u.