'Generate a random number 10% of the time, otherwise generate 0
In Python I would like to create a distribution that picks a random number between 5 and 10, 10% of the time. The other 90% of the time, I would like it to pick zero.
I would like to sample 10,000 numbers.
Solution 1:[1]
You can use numpy.random.choice:
import numpy as np
nums = list(range(5, 10+1))
# [5, 6, 7, 8, 9, 10]
out = np.random.choice([0]+nums, p=[.9]+[.1/len(nums)]*len(nums), size=10000).tolist()
distribution of values:
alternative
Other approach, if you want exactly 90% of 0 and the rest divided in exactly the same number of each value and the order needs to be random:
nums = list(range(5, 10+1))
out = nums*1000+[0]*9000
import random
random.shuffle(out)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

