How to weight or bias the 'Rand' function

If I want a random integer from 1 to 4 but I want to bias the distribution, how do I do that?

For example: int(Rand(1, 4))

I want a random series of numbers in my loop, but I want to bias it toward more 1’s then, 2’s then 3’s then 4’s, with 4’s being approximately 10% of the series. Thank you.


There are many possibilities, but here is one using an (overkill) power function. The exponent is computed such that 10% of the results is 4.

exponent = math.log(0.75, 0.9)
r = int(pow(random.random(), exponent)) + 1

Thank you, Brecht. I’ll try this and get back to you. is ‘random’ part of the noise function? Excuse my ignorance, but is the 1 to 4 contained in the setup of your exponent values 0.75 and 9? Thanks again.


I made a mistake, leaving out the *4, it’s not in the exponent. random is a standard python module, but you can use some other function too that gives numbers in the range 0-1.

exponent = math.log(0.75, 0.9)
r = int(pow(random.random(), exponent))*4 + 1

But really if it’s just for 4 integers, you can do something simpler and just pick some floating point numbers randomly, like:

f = random.random()
if f < 0.5: r = 1
elif f < 0.75: r = 2
elif f < 0.9: r = 3
else: r = 4

Thank you so much. If the value is 0.3 it will evaluate the first expression true and not go to the others right? Otherwise, 0.3 would set r = 1, 2, 3 and 4. Thanks.