This is a one dimensional case study of Monte Carlo integration from the Ray Tracing: the Rest of Your Life book.

Let’ s look at an integral:

We can solve it analytically and get a result . But for the sake of demostration we will use Monte Carlo integration for this problem.

Uniform Sampling

We might write this as:

We could also write it as:

This suggests a Monte Carlo approach:

auto sum = 0.0;
for (int i = 0; i < N; i++) {
  const double x = uniform_random(0,2);
  sum += x * x;
}
const auto I = 2 * sum / N;

We gets the expected anwser

We can use this method even for integrals without a analytical solution like , which is what we often need to do for all but the most trivial functions.

Importance Sampling

A problem of the above approach is that our uniform sampler may not sample certain points often enough (for example, thinking about small light sources when sampling the rendering equation), which courses slow convergent rate. We can solve this problem by using importance sampling.