Olivia Cassendre
Olivia Cassendre

Reputation: 11

Python Random Selection

I have a code which generates either 0 or 9 randomly. This code is run 289 times...

import random
track = 0
if track < 35:
    val = random.choice([0, 9])
    if val == 9:
        track += 1
    else:
        val = 0

According to this code, if 9 is generated 35 times, then 0 is generated. So there is a heavy bias at the start and in the end 0 is mostly output.

Is there a way to reduce this bias so that the 9's are spread out quite evenly in 289 times.

Thanks for any help in advance

Upvotes: 1

Views: 156

Answers (2)

grill
grill

Reputation: 1170

It sounds like you want to add some bias to the numbers that are generated by your script. Accordingly, you'll want to think about how you can use probability to assign a correct bias to the numbers being assigned.

For example, let's say you want to generate a list of 289 integers where there is a maximum of 35 nines. 35 is approximately 12% of 289, and as such, you would assign a probability of .12 to the number 9. From there, you could assign some other (relatively small) probability to the numbers 1 - 8, and some relatively large probability to the number 0.

Walker's Alias Method appears to be able to do what you need for this problem.

General Example (strings A B C or D with probabilities .1 .2 .3 .4):

abcd = dict( A=1, D=4, C=3, B=2 )
# keys can be any immutables: 2d points, colors, atoms ...
wrand = Walkerrandom( abcd.values(), abcd.keys() )
wrand.random()  # each call -> "A" "B" "C" or "D"
    # fast: 1 randint(), 1 uniform(), table lookup

Specific Example:

numbers = dict( 1=725, 2=725, 3=725, 4=725, 5=725, 6=725, 7=725, 8=725, 9=12, 0=3 )
wrand = Walkerrandom( numbers.values(), numbers.keys() )
#Add looping logic + counting logic to keep track of 9's here
track = 0
i = 0
while i < 290
    if track < 35:
        val = wrand.random()
        if val == 9:
            track += 1
    else:
        val = 0
    i += 1

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308548

Apparently you want 9 to occur 35 times, and 0 to occur for the remainder - but you want the 9's to be evenly distributed. This is easy to do with a shuffle.

values = [9] * 35 + [0] * (289 - 35)
random.shuffle(values)

Upvotes: 1

Related Questions