Monte Carlo Simulations in Python
Izzy Weber
Curriculum Manager, DataCamp
Monte Carlo simulations are used in fields such as...
Roll two separate dice from two bags, each containing three biased dice:
bag1 = [[1, 2, 3, 6, 6, 6], [1, 2, 3, 4, 4, 6], [1, 2, 3, 3, 3, 5]]
bag2 = [[2, 2, 3, 4, 5, 6], [3, 3, 3, 4, 4, 5], [1, 1, 2, 4, 5, 5]]
Simulation:
def roll_biased_dice(n): results = {}
for i in range(n): bag_index1 = random.randint(0, 2) die_index1 = random.randint(0, 5) bag_index2 = random.randint(0, 2) die_index2 = random.randint(0, 5)
point1 = bag1[bag_index1][die_index1] point2 = bag2[bag_index2][die_index2]
key = "%s_%s" % (point1, point2)
if point1 + point2 == 8: if key not in results: results[key] = 1 else: results[key] += 1
dice1_dice2 | probability_of_success |
---|---|
6_2 | 5.54 |
3_5 | 2.67 |
2_6 | 1.45 |
4_4 | 4 |
bag1 = [[1, 2, 3, 6, 6, 6], [1, 2, 3, 4, 4, 6], [1, 2, 3, 3, 3, 5]]
bag2 = [[2, 2, 3, 4, 5, 6], [3, 3, 3, 4, 4, 5], [1, 1, 2, 4, 5, 5]]
Simulation results of 10,000 trials:
bag1 = [[2, 2, 3, 4, 6, 6], [1, 2, 2, 4, 6, 6], [1, 2, 3, 3, 3, 3]]
bag2 = [[1, 2, 3, 4, 5, 6], [1, 3, 3, 4, 4, 6], [2, 2, 2, 3, 5, 5]]
Simulation results of 10,000 trials:
Monte Carlo Simulations in Python