Output of program does not match formula (Probability problem)

Viewed 65

I'm trying to solve this problem for school. I wrote some code for it, however I am not sure if my code is correct because when I checked website (linked below) for the formula to solve the problem, my output does not align with the answers of the formula, I was wondering what I am missing or if I am doing something wrong.

This is the link with the problem and the mathematical solution: https://math.stackexchange.com/questions/1110006/n-players-throw-a-die-and-get-score-for-each-pair-who-throw-the-same-number

I only have the mean so far because I didn't bother to get the variance seeing that the results of the mean were different.

This is the code:

import random

dice = [1, 2, 3, 4, 5, 6]

def dice_a (n, sims):
    scores= []
    sim_counter = 0

    scores_ctr = {}
    
    for x in range(n // 2): 
        scores_ctr[x + 1] = 0
    
    while sim_counter != sims:
        score = 0

        rolls = random.choices(dice, k=n)
        pairs = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}

        for x in rolls:
            pairs[x] += 1 
            if pairs[x] == 2:
                score += 1
                pairs[x] = 0

        scores.append(score)
        scores_ctr[score] += 1
        sim_counter += 1

    mean = 0
    for x, y in scores_ctr.items():
        mean += x * (y/1000)

    return mean

print(dice_a(7, 1000))

Hope to get some help!

Thank you so much!

1 Answers

The error is in the way you calculate the number of pairs with the same dices.

Let's say you have the next dice throws:

[1, 1, 1, 1, 1, 1, 1]

The way you calculate it right now your number of pairs and the total score will be 3, though the correct one is 21. You just found the next pairs:

  1. The first and the second players.
  2. The third and the fourth.
  3. The fifth and the sixth.

And it's wrong because there are more pairs with the same dice throws. Like:

  1. 1st and 2nd.
  2. 1st and 3rd.
  3. 1st and 4th. ...

The correct way to calculate it will be using combination.

Or in the code:

for x in rolls:
    pairs[x] += 1
for val in pairs.values():
    if val > 1:
        score += math.factorial(val) // (2 * math.factorial(val - 2))
if score not in scores_ctr: 
    scores_ctr[score] = 0
scores_ctr[score] += 1
Related