# Limiting range when sampling normal distribution

When sampling a normal distribution is there a way to limit the output, or limit the range of the number generated? For example, if I wanted to simulate a beam that has a gaussian shape I would use 2D gaussian sampling from Gaus():

TRandom3 r(0);
BeamPositionX = r.Gaus(x, sigma_x);
BeamPositionY = r.Gaus(y, sigma_y);

Will output random values centered at (x,y) and the width of this gaussian is determined by sigma_x and sigma_y, but what if I wanted to cut off the range of BeamPositionX and BeamPositionY because the randomly generated outputs are outside the range with respect to the beam window?

I know that I could put a conditional statement:
if(BeamPositionX > xUpperLimit || BeamPositionX < xLowerLimit){repeat sampling}
But I wanted to avoid repeating these kinds of calculations if possible, and hope that there may be something already implemented that limits this range.

Thanks,
Javier

_ROOT Version: 6.26.10
Platform: Not Provided
Compiler: Not Provided

Welcome to the ROOT forum.

I guess @moneta can help.

Hi,
Generating random number according to the normal distribution is quite fast, so if your acceptance range is quite large is still efficient throwing some numbers away applying a conditional statement.
Otherwise you can also create a TF1 (or TF2) object in a given range and use `TF1::GetRandom`. This operations performs a small approximation, by binning the function, but if you use a not too small binning the result should be fine. Otherwise you can also use `UNURAN` with the `TUnuran` and `TUnuranContDist` class, see the tutorial unuranDemo.C

Lorenzo

Thank you! This is exactly what I needed.