I have tried creating a program in Python where a Monte Carlo method is used to estimate the probability of the sum of two dice being 7.
The result I get is nothing close to the theoretical probability. I just now started coding in Python, so I am struggling to locate where the mistake is. Please let me know!
import random
import math
def monte_carlo_estimation():
sum_seven = 1
dice_thrown = 1
prob = 0
for z in range(0, 100):
x = random.uniform(1, 6)
y = random.uniform(1, 6)
sum_wanted = x y == 7
if sum_wanted:
sum_seven = 1
dice_thrown = 1
prob = sum_seven/dice_thrown
print("Estimate: " str(prob))
if __name__ == '__main__':
monte_carlo_estimation()
CodePudding user response:
random.uniform()
returns a random floating point number. So your dice throws will have fractions, and the sums will practically never be exactly 7.
Since dice can only have integer values, you should use random.randint(1, 6)
instead of random.uniform(1, 6)
.
Also you need to initialize your counters to 0
, not 1
. And the line prob = sum_seven/dice_thrown
should be indented one level less; there's no point in updating it every iteration, since you only care about the final value.