# Quick way to approximate a truncated gaussian distribution?

I'm doing some procgen stuff and I need a truncated gaussian distribution. Basically, I need a way to get the same thing as this:

import random
def truncated_gaussian(mean, deviation, min, max):
while True:
val = random.gauss(mean, deviation)
if min < val < max: return val


except without so much wasted effort. It looks like this is a pretty complicated thing to do properly, but I don't need statistics-grade perfect randomness, just a video-game-grade approximation.

Anyone know a trick to make this work?

• You might also be able to do this via inverse transform sampling, re-scaling the CDF to your desired range and clamping it before sampling the resulting function's inverse. I think you'd want to approximate it as a spline since it's not expressible in elementary functions... – DMGregory Sep 1 '19 at 7:51

• Yes, that's the idea. You can index into the array using a modulus operator. Like if it's called nextIndex you could grab the next random number by doing foo = randoms [ nextIndex ]; nextIndex = (nextIndex + 1) % kNumRandoms; – user1118321 Sep 1 '19 at 5:29