Reputation: 1345
I would like to generate a random number between x
and y
with a known probability. For example, using Output=randint(0,2)
i know that there is a 33% probability that Output
is equal to 1.
Similarly, if Output=randint(0,3)
i know that there is 25% probability that the Output
is equal to 1.
How can i generate a random number similar to above to make sure that there is 40% probability that Output
equal to 1?
Thanks a lot
Upvotes: 0
Views: 970
Reputation: 2228
Here I have an alternative solution, looks shorter and since there are no if
statements it should be much faster.
Also, you can easily change what number is to be returned with the 60% probability
a = [1,1,0,0,0]
num = a[randint(0,4)]
As alternative here is a version of the same with a single line:
num = list((1,1,0,0,0))[randint(0,4)]
Upvotes: 1
Reputation: 5074
Not sure what's your aim here, how about getting 40% by giving a fixed range, and than manipulating the results?
For example, this will give you 40% value of 1, and 30% of 2 or 3
num = randint(0,9)
if num <= 3:
num = 1
elif num <= 6:
num = 2
else:
num = 3
Upvotes: 1