[Tutor] Graphing the random.gauss distribution
Kent Johnson
kent37 at tds.net
Tue Aug 14 15:47:07 CEST 2007
Dick Moores wrote:
> Kent Johnson posted this to Tutor list Aug 8, 2007
> (<http://mail.python.org/pipermail/tutor/2007-August/056194.html>):
>
> ============================================
> > Python provides you with a pseudo random number generator whose output
> > values are uniformly distributed between the input parameters. What you
> > are dealing with in fish weights or test scores or other natural
> > phenomena is most likely a normal distribution. Check out Wikipedia's
> > normal distribution entry. The math is really juicy. You may end up
> > with a recipe for the Python Cookbook.
>
> No need for all that, use random.gauss()
>
> Kent
> ============================================
>
> I hadn't noticed gauss was there in the Random module. I got to
> wondering if I could graph the distribution. This code produces a
> nice bell-curve-seeming curve (on its side). Takes about 80 secs to
> run on my computer. To fit your situation, the length of the bars can
> be shortened or lengthened by decreasing or increasing, respectively,
> the divisor of gaussCalls in line 5, "barLengthAdjuster = gaussCalls//2600".
>
> Dick Moores
>
> ==============================
> from random import gauss
> mean = 100
> std = 10
> gaussCalls = 10000000
> barLengthAdjuster = gaussCalls//2600
>
> d = []
> for k in range(200):
> d.append([k, 0])
This could be a list comprehension:
d = [ [k, 0] for k in range(200) ]
but there is no need to keep the array index in the array so this is
simpler:
d = [0] * 200
> for k in xrange(gaussCalls):
> n = int(gauss(mean, std))
> d[n][1] += 1
This becomes just
d[n] += 1
>
> for c in d:
> barLength = c[1]//barLengthAdjuster
> print barLength, "=", c[0], c[1]
Use enumerate() to get the indices as well as the list contents. This
version prints an actual bar as well:
for i, count in enumerate(d):
barLength = count//barLengthAdjuster
print i, '*' * barLength, count
Kent
More information about the Tutor
mailing list