Member-only story
Monte Carlo Simulation: MPI4Py
Monte Carlo simulations are a statistical technique that allows for solving problems through random sampling. They are widely used in various fields such as physics, finance, and engineering to understand the impact of risk and uncertainty in prediction and forecasting models. The core idea is to use randomness to solve problems that might be deterministic in nature. You can visit the detailed tutorial here.
For example, to estimate the value of Pi ((\pi)), we can use the Monte Carlo method. We generate random points in a unit square and count how many fall within a quarter-circle inscribed within the square. The ratio of the points inside the quarter-circle to the total number of points approximates (\pi/4).
Detailed Program
Below is a Python program used mpi4py
for parallel processing in a Monte Carlo simulation to estimate the value of Pi.
from mpi4py import MPI
import numpy as np
import random
def monte_carlo_pi(num_samples):
count = 0
for _ in range(num_samples):
x, y = random.random(), random.random()
if x**2 + y**2 <= 1:
count += 1
return countdef main():
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size() num_samples_per_proc = 1000000 # Adjust as…