Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Statistical Simulation in Python

Cursus bekijken

Oefeninstructies

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

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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))
Code bewerken en uitvoeren