Integrate the function \(f(\mathbf x) = \sqrt{1+|\mathbf x|^2}\) over the 10-dimensional unit cube \([0, 1]^{10}\) using the Monte-Carlo method.
Answer.
f = @(x) sqrt(1 + x*x');
d = 10;
N = 1e6;
s = 0;
for k = 1:N
x = rand(1, d);
s = s + f(x);
end
disp(s/N)
The output is, of course, random, but usually it is about 2.069. If your computer handles a million samples (
N = 1e6) easily, you may want to try 1e7. It would be tedious to compute this integral with WolframAlpha; just entering the limits would take long.
The above code is not vectorized: it uses a loop to evaluate \(f\) at consecutive points. One could generate all these points at once with
rand(N, d) and try to get all values of \(f\) at once. But this requires coding f in such a way that it can consume a matrix and produce a vector of values, and this may be difficult.
