Search code examples
pythonnumpyrandomprobabilitydice

How do i keep my loop from repeating my random values?


So i was learning how to handle probabilities and how to plot them in Python. I came across a problem where i needed to find the probability of the sum of 2 dices being > 7 or odd. I know the result is around 75% but it was translating that to Python that i had a problem with. My code to solve the problem is something like this:

import random
import numpy as np
dice = [1,2,3,4,5,6]
value = 0
simulation_number = len(dice)**2
percentage = []
for i in range(0,simulation_number):
    dice1 = random.choice(dice)
    dice2 = random.choice(dice)
    random_match = dice1,dice2
    
    if (sum(random_match))>7 or (sum(random_match)%2) != 0:
        value += 1
percentage.append(np.round((value/simulation_number)*100,2))
print(percentage,"%")

It works just fine but everytime i run the code it gives a different solution because the loop is repeating outcomes for random_match. How do I include in the code the condition of not repeating random_match values?


Solution

  • Generating random values from 1 to 6 won't work. Assume that you are tossing a coin 10 times. theoretically you should get 5 heads and 5 tails. But that does not happens in real life because of sampling error. When you generate random values, there is always some sampling error.

    import random
    import numpy as np
    dice = [1,2,3,4,5,6]
    value = 0
    simulation_number = len(dice)**2
    for i in range(len(dice)):
        for j in range(len(dice)):
            dice1 = dice[i]
            dice2 = dice[j]
            x = dice1+dice2
            if x>7 or x%2== 1:
                value += 1
    percentage = np.round((value/simulation_number)*100,2)
    print(f'{percentage} %')
    

    This works as you need every case only once. Using random might take same case again and again