vivian
vivian

Reputation: 151

python simulation of actual number of occurrence given theoretical probabilities

The goal is to simulate the actual number of occurrence given theoretical probabilities.

For example, a 6-faces biased dice with probability of landing (1,2,3,4,5,6) being (0.1,0.2,0.15,0.25,0.1,0.2). Roll the dice for 1000 times and output simulated number of getting each face.

I know numpy.random.choices offer the function to generate each rolling, but I need kind of summary of number of landing of each face. What is the optimal scripts with Python for above?

Upvotes: 2

Views: 485

Answers (2)

Fractal
Fractal

Reputation: 814

Can be done without Numpy too.

import random
random.choices([1,2,3,4,5,6], weights=[0.1,0.2,0.15,0.25,0.1,0.2], k=1000)

Upvotes: 0

Jérôme Richard
Jérôme Richard

Reputation: 50488

Numpy can be used to do that easily and very efficently:

faces = np.arange(0, 6)
faceProbs = [0.1, 0.2, 0.15, 0.25, 0.1, 0.2]        # Define the face probabilities
v = np.random.choice(faces, p=faceProbs, size=1000) # Roll the dice for 1000 times
counts = np.bincount(v, minlength=6)                # Count the existing occurrences
prob = counts / len(v)                              # Compute the probability

Upvotes: 3

Related Questions