snk
snk

Reputation: 91

How do I generate dice rolls with different probabilities?

just working on a homework question where it asks to produce a dice rolling program where one or two numbers may be more likely to print than the rest. For example 2 and/or 3 might be 10% or 20% more likely to print than other elements on the dice. I got the code up to the point where I can get it to print a random number on the dice but can't figure out how to have a weighted output.

input:

  def roll_dice(n, faces = 6):
    rolls = []
    rand = random.randrange

    for x in range (n):

      rolls.append(rand(1, faces + 1 ))

    return rolls

  print (roll_dice(5))

output: [5, 11, 6, 7, 6, 5]

Upvotes: 1

Views: 1419

Answers (2)

visibleman
visibleman

Reputation: 3315

If you are on Python 3

import random
rolls = random.choices([1,2,3,4,5,6],weights=[10,10,10,10,10,50], k=10)

rolls
out:[1, 3, 2, 5, 3, 4, 6, 6, 6, 4]

Upvotes: 0

Nicolas Gervais
Nicolas Gervais

Reputation: 36584

from scipy import stats
values = np.arange(1, 7) 
prob = (0.1, 0.2, 0.3, 0.1, 0.1, 0.2) # probabilities must sum to 1
custm = stats.rv_discrete(values=(values, prob))

for i in range(10):
    print(custm.rvs())

1, 2, 3, 6, 3, 2, 3, 2, 2, 1

Source: scipy.stats.rv_discrete

Upvotes: 1

Related Questions