Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you provide a simple example of Monte Carlo integration in Python


Can you provide a simple example of Monte Carlo integration in Python


Here is a simple example of Monte Carlo integration in Python:

python
import numpy as np
import matplotlib.pyplot as plt

# Define the function to integrate
def f(x):
    return x * np.cos(71 * x) + np.sin(13 * x)

# Generate random points
n = 100
reps = 1000
x = f(np.random.random((n, reps)))

# Calculate the Monte Carlo estimate
y = 1 / np.arange(1, n + 1)[:, None] * np.cumsum(x, axis=0)
upper, lower = np.percentile(y, [2.5, 97.5], axis=1)

# Plot the results
plt.plot(np.arange(1, n + 1), y, c='grey', alpha=0.02)
plt.plot(np.arange(1, n + 1), y[:, 0], c='red', linewidth=1)
plt.plot(np.arange(1, n + 1), upper, 'b', np.arange(1, n + 1), lower, 'b')
plt.show()

In this example, we:

1. Define a function `f(x)` that we want to integrate.
2. Generate `n` random points `x` between 0 and 1, and evaluate the function `f(x)` at those points `n` times, resulting in a 2D array `x` of shape `(n, reps)`.
3. Calculate the Monte Carlo estimate `y` by taking the cumulative sum of the function evaluations and dividing by the number of samples.
4. Compute the 2.5% and 97.5% percentiles of the Monte Carlo estimates to get a 95% confidence interval.
5. Plot the results, showing the individual Monte Carlo estimates in grey, the mean estimate in red, and the 95% confidence interval in blue.

The key steps are:

1. Define the function to integrate
2. Generate random samples of the input variable
3. Evaluate the function at those samples
4. Take the average of the function evaluations to estimate the integral

This simple example demonstrates the basic Monte Carlo integration technique in Python. More advanced techniques like variance reduction can be used to improve the convergence rate.

Citations:
[1] https://www.youtube.com/watch?v=EnsWVUjpqDE
[2] https://www.geeksforgeeks.org/monte-carlo-integration-in-python/
[3] https://www.youtube.com/watch?v=WAf0rqwAvgg
[4] https://people.duke.edu/~ccc14/sta-663/MonteCarlo.html
[5] https://github.com/monte-carlo-data/monte-carlo-python-sdk-examples