1

Suppose I have a coin with that lands on heads with probability P. The experiment to be performed is to continue flipping the coin x number of times. This experiment is to be repeated 1000 times.

Question Is there an efficient/vectorized approach to generate an array of random 1's(with probability P) and 0's (with probability 1-P)?

If I try something like this:

np.full(10,rng().choice((0,1),p= [.3,.7]))

The entire array is filled with the same selection. I have seen solutions that involve a fixed ratio of zeros to ones.

a = np.ones(n+m)
a[:m] = 0
np.random.shuffle(a) 

However I'm not sure how to preserve the stochastic nature of the experiments with this set up.

Presently I am just looping through each iteration as follows, but it is very slow once the number of experiments gets large.

(The actual experiment involves terminating each trial when two consecutive heads are flipped, which is why there is a while loop in the code. For purposes of making the question specific I didn't want to address that here. )

Set = [0,1]
T = np.ones(Episodes)
for i in range(Episodes):
    a = rng().choice(Set, p=[(1 - p), p])
    counter = 1
    while True:
        b = rng().choice(Set, p=[(1-p),p])
        counter += 1
        if (a == 1) & (b == 1):
            break
        a = b
    T[i] = counter

Any insights would be appreciated, thanks!

phntm
  • 511
  • 2
  • 11
  • 2
    `np.random.choice([0,1], p=[.3,.y], size=(1000, x) ) `? – Quang Hoang Mar 25 '21 at 17:32
  • 1
    I think you can use ```numpy.random.binomial``` since a bernoulli distribution is just a special case of binomial distribution. – Kevin Mar 25 '21 at 17:33
  • 1
    Does this answer your question? [Generate random array of 0 and 1 with a specific ratio](https://stackoverflow.com/questions/21566744/generate-random-array-of-0-and-1-with-a-specific-ratio) – G. Anderson Mar 25 '21 at 17:33
  • oh awesome thanks! I don't really know what i'm doing so this is very helpful. So i guess with the default_rng() the code would look like rng().binomial(1, p = .7, size=(10,10)) or rng().choice((0,1),p = [.3,.7], size=(10,10)) – phntm Mar 25 '21 at 17:55

1 Answers1

1

Answers provided by @Quang Hong and @Kevin as listed in the comments above. Just reposting with default_rng() so it is easier to reference later. But they are the true heroes here.

from numpy import default_rng as rng 

rng().binomial(1, p = .7, size=(10,10))

rng().choice((0,1),p = [.3,.7], size=(10,10))
phntm
  • 511
  • 2
  • 11