Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "randomly" select numbers with a specified bias toward a particular number

How do I generate random numbers with a specified bias toward one number. For example, how would I pick between two numbers, 1 and 2, with a 90% bias toward 1. The best I can come up with is...

import random

print random.choice([1, 1, 1, 1, 1, 1, 1, 1, 1, 2])

Is there a better way to do this? The method I showed works in simple examples but eventually I'll have to do more complicated selections with biases that are very specific (such as 37.65% bias) which would require a very long list.

EDIT: I should have added that I'm stuck on numpy 1.6 so I can't use numpy.random.choice.

like image 206
b10hazard Avatar asked Aug 26 '14 13:08

b10hazard


2 Answers

np.random.choice has a p parameter which you can use to specify the probability of the choices:

np.random.choice([1,2], p=[0.9, 0.1])
like image 94
unutbu Avatar answered Sep 20 '22 23:09

unutbu


The algorithm used by np.random.choice() is relatively simple to replicate if you only need to draw one item at a time.

import numpy as np

def simple_weighted_choice(choices, weights, prng=np.random):
    running_sum = np.cumsum(weights)
    u = prng.uniform(0.0, running_sum[-1])
    i = np.searchsorted(running_sum, u, side='left')
    return choices[i]
like image 28
Robert Kern Avatar answered Sep 17 '22 23:09

Robert Kern