Biased random?
Jun-geun Park
Junkeun.park at gmail.com
Tue Aug 28 00:46:45 EDT 2007
Jun-geun Park wrote:
> Ivan Voras wrote:
>> Hi,
>>
>> I have a list of items, and need to choose several elements from it,
>> "almost random". The catch is that the elements from the beginning
>> should have more chance of being selected than those at the end (how
>> much more? I don't care how the "envelope" of probability looks like at
>> this point - can be linear). I see that there are several functions in
>> Python standard libraries for various distribution, but is there an easy
>> pythonic way to make them do what I need?
>>
>>
>
> That's weird. random.randint(a,b) will be enough for most cases. Test
> your system to see the distribution is uniform with something like:
>
> ----
> import random
>
> dist = {}
> for z in xrange(100000):
> u = random.randint(1,10)
> try:
> dist[u] = dist[u] + 1
> except KeyError:
> dist[u] = 1
>
> print dist
> ----
I understood the question wrong.(Thanks, Grant and Robert.) To get the
linear
distribution, you can start from the following:
a = (random.random() + random.random())/2.0 # Triangle distribution
in [0,1)
b = random.random() #
Uniform in [0,1)
c = b + (1-b)*a
# Convolution
u = int(100*(1-c)+1)
# ceil(100*(1-c))
, then, because convolution of a rectangle function and a triangle
function is a
linear function under the valid domain, u is a random integer in [1,100]
that follows (decreasing) linear distribution.
Alternatively if I were in your case, I would go with an exponential
random with
a suitable lambda(by cutting its tail.)
More information about the Python-list
mailing list