Using scipy.stats.bernoulli to simulate 1/3 probability

631 Views Asked by At

Our task is to recreate the famous fair coin flip (p=0.5) using only bernoulli.rvs() to generate function with uniform discrete distribution (outcomes = 0,1,2). Is it possible to do using only bernoulli function form scipy.stats?

1

There are 1 best solutions below

0
On

Yes, it's possible using acceptance/rejection (as you described in a comment). I'm not sure why you asked this since you seem to know how to do it, but since nobody has posted an implementation yet here you go:

from scipy.stats import bernoulli
import numpy as np

MATCHSET = np.array([[0,0], [0,1], [1,0]])

def gen_uniform_3():
    while True:
        ary = bernoulli.rvs(1/2, size = 2)
        for i in range(3):
            if np.array_equal(ary, MATCHSET[i]):
                return i

The while True will keep trying as long as the generated pair is [1,1], but will return a value of 0, 1, or 2 for the other three equally likely outcomes.