Search code examples
pythonrandomsimulationnormal-distribution

How to simulate random normal variate Python


First of all, I am extremely new with coding. I received an assignment to "Simulate many normally distributed random numbers, then calculate mean and standard deviation." using Python. To begin with, I'm having some difficulties interpreting the question.

Anyway, I think I've figured out how to generate a wished number of random numbers from a standard normal distribution using a for loop (though I'm not sure this is what's asked for). What I'm struggling with is to use these numbers for calculations - since they are random I don't know how to use lists.


Solution

  • You can generate the random numbers using random.gauss. For example I'll create a list of 10 random numbers, with a mean of 10 and standard deviation of 1

    >>> import random
    >>> nums = [random.gauss(10, 1) for _ in range(10)]
    >>> nums
    [11.959067391283675, 9.736968009359552, 9.034607376861388, 9.431664007796622, 11.522646114577977, 9.777134678502273, 10.954304068858296, 9.641278997034552, 10.671349950944085, 10.795117781051463]
    

    Then you can use the statistics library to calculate mean and standard deviation.

    >>> import statistics as stats
    
    >>> avg = stats.mean(nums)
    >>> avg
    10.352413837626989   # pretty close to 10
    
    >>> stddv = stats.stdev(nums)
    >>> stddv
    0.9667002670583574   # pretty close to 1
    

    You can see that if I generated a lot of random numbers, assuming the random library has a good implementation of sampling numbers from a desired distribution, you will get back approximately the mean and standard deviation you used to describe the original distribution.