1. Learn
  2. /
  3. Courses
  4. /
  5. Statistical Simulation in Python

Exercise

Integrating a Simple Function

This is a simple exercise introducing the concept of Monte Carlo Integration.

Here we will evaluate a simple integral \( \int_0^1 x e^{x} dx\). We know that the exact answer is \(1\), but simulation will give us an approximate solution, so we can expect an answer close to \(1\). As we saw in the video, it's a simple process. For a function of a single variable \(f(x)\):

  1. Get the limits of the x-axis \((x_{min}, x_{max})\) and y-axis \((\max(f(x)), \min(\min(f(x)), 0))\).
  2. Generate a number of uniformly distributed point in this box.
  3. Multiply the area of the box (\((\max(f(x) - \min(f(x))\times(x_{max}-x_{min})\)) by the fraction of points that lie below \(f(x)\).

Upon completion, you will have a framework for handling definite integrals using Monte Carlo Integration.

Instructions

100 XP
  • In the sim_integrate() function, generate uniform random numbers between xmin and xmax and assign to x.
  • Generate uniform random numbers between \(\min(\min(f(x)), 0)\) and \(\max(f(x))\) and assign to y.
  • Return the fraction of points less than \(f(x)\) multiplied by area (\((\max(f(x) - \min(f(x))\times(x_{max}-x_{min})\)) .
  • Finally, use lambda function to define func as \(x e^{x}\).