Get startedGet started for free

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.

This exercise is part of the course

Statistical Simulation in Python

View Course

Exercise instructions

  • 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}\).

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Define the sim_integrate function
def sim_integrate(func, xmin, xmax, sims):
    x = np.random.uniform(____, ____, sims)
    y = np.random.uniform(____, ____, sims)
    area = (max(y) - min(y))*(xmax-xmin)
    result = area * sum(____(____) < abs(func(x)))/sims
    return result
    
# Call the sim_integrate function and print results
result = sim_integrate(func = lambda x: ____, xmin = 0, xmax = 1, sims = 50)
print("Simulated answer = {}, Actual Answer = 1".format(result))
Edit and Run Code