Monte Carlo Simulation, also known as the Monte Carlo Method or a multiple probability simulation, is a mathematical technique, which is used to estimate the possible outcomes of an uncertain event. The Monte Carlo Method was invented by John von Neumann and Stanislaw Ulam during World War II to improve decision-making under uncertain conditions.
Unlike a normal forecasting model, Monte Carlo Simulation predicts a set of outcomes based on an estimated range of values versus a set of fixed input values.
Example 1
Problem: the probability of three heads and two tails for a coin tossed five times (assuming a fair coin)
Answer (from Maths Probability theory) : binomial(3 + 2, 3) 2^(-(3 + 2)) = ((3 + 2)!)/(3! 2! 2^(3 + 2))= 5/16 ≈ 0.3125
Example 2
Problem: The probability of getting three consecutive Heads at the beginning if a coin is tossed 5 times
Answer (Using Probability theory): ½ X ½ X 1/2 = ⅛ = 0.125
The Mathematical model of Monte Carlo written in Python
Problem 1
import random
def calculateprobability1(attempts):
"""
Calculates the probability of a specific outcome by running a simulation.
The simulation involves summing five random integers (0 or 1).
A 'success' is recorded if the sum is exactly 3.
Args:
attempts (int): The number of times to run the simulation.
Returns:
float: The calculated probability of success.
"""
success = 0
for _ in range(attempts):
sum_of_rolls = (
random.randint(0, 1) +
random.randint(0, 1) +
random.randint(0, 1) +
random.randint(0, 1) +
random.randint(0, 1)
)
if sum_of_rolls == 3:
success += 1
print("Number of attempts = ", attempts)
print("Number of success = ", success)
return success / attempts
# Example usage:
# probability = calculateprobability1(10000)
# print("Calculated Probability =", probability)
Problem 2
import random
def calculateprobability2(attempts):
"""
Calculates the probability of getting three consecutive successes (represented by 1)
in a series of random trials.
Args:
attempts (int): The number of trials to run the simulation.
Returns:
float: The estimated probability of a success, based on the simulation.
"""
success = 0
for _ in range(attempts):
# A 'success' is defined as three consecutive random integers
# from a range of [0, 1] being exactly 1.
if (random.randint(0, 1) == 1 and
random.randint(0, 1) == 1 and
random.randint(0, 1) == 1):
success += 1
print("Number of attempts =", attempts)
print("Number of success =", success)
return success / attempts
# Example usage:
# probability = calculateprobability2(100000)
# print(f"Estimated probability: {probability}")
The Monte Carlo examples implemented in Python...
Top comments (0)