Home > Back-end >  Generate random number in python, such that the likelihood of a number being generated is inversely
Generate random number in python, such that the likelihood of a number being generated is inversely

Time:02-15

I want to generate a pseudo random number from 1 to n in python, but the likelihood of a number being generated should be lesser the higher the number is. So, 1 will be the most likely outcome of this random function 2 will be half as likely as 1 3 will be one-third as likely as 1 4 will be one-fourth as likely as 1 ... k will be 1/k as likely as 1.

So if there's a 1/10 chance the outcome will be 1, the chance for 2 will be 1/20, 3: 1/30, k: 1/10k.

I don't want to make a list and choose a random value or any such inaccurate hacks so don't suggest that.

CodePudding user response:

Would you accept an accurate hack?

random.choices(range(1,n 1),[1/k for k in range(1,n 1)])

works. Furthermore it has an optional parameter k which lets you generate as many random numbers as you need.

CodePudding user response:

The Scipy package can generate random reciprocals as described here

In this example, we create a single random value from the range N = 1 - 10:

from scipy.stats import reciprocal
>>> r = reciprocal.rvs(1, 10, size=1)
>> r
array([ 3.83178852])

The returned value is an array of size elements.

  • Related