Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Monte Carlo Method to estimate the probability of the sum of two dice thrown being 7

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading