steve at REMOVE-THIS-cybersource.com.au
Sat Feb 27 03:52:54 CET 2010
On Fri, 26 Feb 2010 13:26:44 -0800, pistacchio wrote:
> i'm trying the random.gauss function. can anyone explain how to get a
> number between a given range? like, from 0 to 20 with an average of 10?
That's not what a Gaussian distribution does. It has an infinite range.
Are you sure you want a Gaussian, and not a uniform distribution or a
You could pin the values to the appropriate range:
def pinned_gaussian(a, b, mu, sigma):
"""Return a Gaussian random number pinned to [a, b]."""
return min(b, max(a, random.gauss(mu, sigma)))
but that will distort the randomness slightly: you will have a slight
excess of values equal to a and b than you otherwise might expect. You
might not care, though, particularly if the sigma is very small relative
to the minimum and maximum you want.
Alternatively, you could use this approach:
def truncated_gauss(a, b, mu, sigma):
"""Return a random number from a truncated Gaussian distribution."""
x = random.gauss(mu, sigma)
if a <= x <= b:
> and how to determine the "steep" of the curve? i've never studied it, so
> mu and sigma don't really tell me a thing.
mu is the average -- in your example above, mu would be 10.
sigma is the standard deviation of the random variable. It tells you how
much the random variable actually varies: if sigma is close to zero, most
of the numbers will be close to mu and the graph will look like a spike;
if sigma is large, it will be very broad and flat.
Statistically, the following rules apply:
68% of the numbers will be between (mu - sigma) and (mu + sigma).
95% of the numbers will be between (mu - 2*sigma) and (mu + 2*sigma).
99.7% of the numbers will be between (mu - 3*sigma) and (mu + 3*sigma).
(the percentages are approximate, not exact). So you could get a
reasonable approximation to a normal distribution truncated between 0 and
truncated_gauss(0, 20, 10, 10.0/3)
More information about the Python-list