Home > other >  Generate a random number 10% of the time, otherwise generate 0
Generate a random number 10% of the time, otherwise generate 0

Time:05-01

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.

CodePudding user response:

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:

enter image description here

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)
  • Related