Search code examples
pythonsimulationprobabilitydistribution

How to see a distribution of outcomes of a while loop?


Imagine you have a while loop that includes a random outcome so that the output of the while loop is different each time. How can you simulate the while loop many times and see the distribution of outcomes?

I know how to run the while loop but I don't know how to simulate the loop multiple times and see the outcome distribution. For example, how would I simulate the loop below 100 times and see the distribution of outcomes?

import random

rolls = 0
count = 0
while rolls < 10:
  dice = random.randint(1,6)
  rolls = rolls + 1

  count = count + dice

count

Solution

  • You can make an empty list of all_rolls = [] and then .append() each now roll to it. This will result in a list of numbers, each number being the result of that roll (so all_rolls[0] would be the first roll).

    Then use matplotlib to make your histogram.

    I would also avoid the while loop since you are just incrementing, which is what a for loop over a range is for. I do the for loop with _ instead of using something like i since we don't actually use the value from the range, we just want to do it 10 times.

    import random
    import matplotlib.pyplot as plt
    
    all_rolls = []
    for _ in range(10):
        this_roll = random.randint(1, 6)
        all_rolls.append(this_roll)
    
    plt.hist(all_rolls)
    plt.show()
    

    If you want to run the above 100 times and plot the sums of the rolls for each, then you can wrap that loop in a function and then return the sum of the list, and do that 100 times.

    import random
    import matplotlib.pyplot as plt
    
    
    def my_loop():
        all_rolls = []
        for _ in range(10):
            this_roll = random.randint(1, 6)
            all_rolls.append(this_roll)
        return sum(all_rolls)
    
    
    all_roll_sums = []
    for _ in range(100):
        all_roll_sums.append(my_loop())
    
    plt.hist(all_roll_sums)
    plt.show()