Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading