Search code examples
pythonnumpyscikit-learnprobabilitynormal-distribution

Python - Creating a skewed discrete normal probability distribution for sampling integers


Similarly to the following question:
Create random numbers with left skewed probability distribution

By stating the maximum and variance, I would like to sample integers from some given range.

For example, for the range - {0,1,...,1000} (aka range(1001)), the maximum value is 100 so the sampled numbers would be most likely from the range of [90-110], less likely numbers that would be sampled are [80-89] and [111-120] etc.


Solution

  • The following code will do that:

    import scipy.stats as ss
    import numpy as np
    import matplotlib.pyplot as plt
    
    center = 100
    n = 1001
    std = 20
    x = np.arange(0, n)
    prob = ss.norm.pdf(x,loc=center, scale = std )
    prob = prob / prob.sum() #normalize the probabilities so their sum is 1    
    
    nums = np.random.choice(x, 20, p=prob)
    nums