Creating Random Numbers
In Review
In scientific and management applications it can be very handy to be able to generate large numbers of random numbers that fit a particular distribution. Lets say we are looking a measuring the number of species in a particular size sampling plot. We might expect this be a normal distribution with a given mean and standard deviation. If we were creating a program to model this phenomenon, or using another program to model it, we might want to test the model before we start processing the data or even collecting the data.
Python contains a number of functions to create random numbers with different distributions. The simplest is the randint(a,b) function which will produce random numbers between a and b. Try the following:
import random x=0 while (x<10): y=random.randint(1,100) print(y) x+=1
You should see a set of numbers randomly selected from 1 to 100. Run the program again. Did you get the same numbers?
Now try the code below to create random numbers that are on a normal distribution. Copy and paste the results in to Excel, create a histogram of the data, and see if it looks close to a normal curve. To see how to create a histogram in Excel just go to the help in Excel, search on "Histogram", try to find how to create a histogram, and then go to your favorite search engine on the web and type "Excel Histogram". There will be lots of examples on the web. I'm not kidding here as each version of Excel is a little different and the histogram function is available in the Analysis Toolpak so it has to be installed first. Later we'll learn to create histograms in Python.
import random mu=0 sigma=1 x=0 while (x<10): y=random.normalvariate(mu,sigma) print(y) x+=1
Additional Resources
Further Reading: Python documentation