0

How would one go about generating a list of random numbers from a list of 35 numbers with given probabilities:

Probability of number in range (1,5) - p1 = 0.5

Probability of number in range (6,15) - p2 = 0.25

Probability of number in range (16,35) - p3 = 0.25

I tried using numpy.random.choice() but I have no idea how to jam in possible lists of numbers.

Ehsan
  • 12,072
  • 2
  • 20
  • 33
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. You seem to be asking for a personal tutorial; this is off-topic for Stack Overflow. – Prune Nov 03 '20 at 21:32
  • I assume you meant generate a random number from a list with weights, otherwise please elaborate on what you mean. Thank you. – Ehsan Nov 03 '20 at 21:36
  • @Ehsan No, I meant generate a list of numbers with those weights. Basically generating a discrete source with an alphabet of 35 symbols whose values should be in one of the ranges I mentioned in my question. – Zlatan Radovanovic Nov 03 '20 at 21:55
  • 1
    @ZlatanRadovanovic what is the size of your list you want to generate? is it with or without replacement? You can set them all in arguments of `np.random.choice` in my answer. – Ehsan Nov 03 '20 at 21:57
  • Does this answer your question? [A weighted version of random.choice](https://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choice) – Peter O. Nov 03 '20 at 21:59
  • 1
    @Ehsan I overlooked the size argument in the function, all good now. Thanks. – Zlatan Radovanovic Nov 03 '20 at 22:02

2 Answers2

2

If you want to select uniformly from each group:

p=np.array([0.5/5]*5+[0.25/30]*30)
np.random.choice(np.arange(1,36),p=p/p.sum())

UPDATE:

and if you would like to select a list of random numbers (you can also set with or without replacement flag):

np.random.choice(np.arange(1,36), size=N, replace=True, p=p/p.sum())
Ehsan
  • 12,072
  • 2
  • 20
  • 33
1

You could accomplish this by selecting the appropriate range with the specified probabilities, then use the chosen range as an argument to random.choice:

range_set = [range(1,6), range(6, 16), range(16, 36)]
random.choice(*random.choices(range_set, [0.5, 0.25, 0.25]))

This assumes that you want a uniform choice within a given range.

pjs
  • 18,696
  • 4
  • 27
  • 56