0

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

SBad
  • 1,245
  • 5
  • 23
  • 36
  • 2
    If you are looking for a batteries-included solution, have a look at numpy: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html. If you want to implement it yourself, the key insight is that you can reduce this problem to drawing a random float between 0 and 1 using the cumulative density function. – cel Apr 25 '19 at 11:00
  • `1 if random() < 0.4 else 0`? Surely this must be a duplicate. – John Coleman Apr 25 '19 at 11:13
  • Possible duplicate of [Generate random numbers with a given (numerical) distribution](https://stackoverflow.com/questions/4265988/generate-random-numbers-with-a-given-numerical-distribution) – John Coleman Apr 25 '19 at 11:15
  • Using a cumulative density function is a really good point? do you mean normal density? – SBad Apr 25 '19 at 11:17

2 Answers2

1

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
yuval.bl
  • 4,890
  • 3
  • 17
  • 31
  • 1
    I like this simple approach. I ll go for that thanks a lot. i am doing a simple testing on some randomization problem so i am looking for a quick and dirty approach – SBad Apr 25 '19 at 11:18
1

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)]
Antoan Milkov
  • 2,152
  • 17
  • 30