From: Gregory Ewing on 27 Feb 2010 23:27
Steven D'Aprano wrote:
> 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)))
> def truncated_gauss(a, b, mu, sigma):
> """Return a random number from a truncated Gaussian distribution."""
> while 1:
> x = random.gauss(mu, sigma)
> if a <= x <= b:
> return x
If it doesn't have to be strictly gaussian, another way is to
approximate it by adding some number of uniformly distributed
samples together. If you have n uniform samples ranging from
0 to a, the sum will be in the range 0 to n*a and the mean
will be n*a/2. The greater the value of n, the closer the
distribution will be to normal.