Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Monte Carlo control Python sample code snippets
    Monte Carlo methods Python code integration variance reduction control variate numerical methods matplotlib Python examples


Monte Carlo control Python sample code snippets


Here are some sample code snippets for Monte Carlo methods in Python:

Monte Carlo Integration Example

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()

Monte Carlo Variance Reduction Example

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()

Monte Carlo Control Variate Example

python
import numpy as np
import matplotlib.pyplot as plt

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

def f1(x):
    return x * np.cos(71 * x) + np.sin(13 * x)

# Generate random points
n = 100
reps = 1000
x0 = f0(np.random.random((n, reps)))
x1 = f1(np.random.random((n, reps)))

# Calculate the Monte Carlo estimate
y0 = 1 / np.arange(1, n + 1)[:, None] * np.cumsum(x0, axis=0)
y1 = 1 / np.arange(1, n + 1)[:, None] * np.cumsum(x1, axis=0)

# Calculate the control variate estimate
cv_mean = y0.mean() + (y1.mean() - y0.mean()) * (x1.mean() - x0.mean()) / (x1.mean() - x0.mean())

# Plot the results
plt.plot(np.arange(1, n + 1), y0, c='grey', alpha=0.02)
plt.plot(np.arange(1, n + 1), y1, c='grey', alpha=0.02)
plt.plot(np.arange(1, n + 1), cv_mean, 'b')
plt.show()