# How to generate random variate in custom domain for a distribution?

I have a distribution defined in a particular domain of the variable but now I want to generate a random variable not in the entire domain but only in a subset of the domain. Here is what I'm trying to do

a=0.25*\[Pi];
pdf= ProbabilityDistribution[1/Cos[x]^2, {x, -a, a}, Method -> "Normalize"];
RandomVariate[pdf]


This will generate a random variable from the given distribution between (-a,a). But I want to generate the variable between some subset, say (-a/2,a/2). How do I do this?

I have tried changing the domain of the distribution itself but it is easy to see that this will redefine the whole distribution and is not the same as what I want.

a = 0.25*\[Pi];
pdf = ProbabilityDistribution[1/Cos[x]^2, {x, -a, a},
Method -> "Normalize"];


Create a truncated distribution:

tpdf = TruncatedDistribution[{-a/2, a/2}, pdf];


Get the Min/Max of a bunch...

MinMax@RandomVariate[tpdf, 1*^6]


{-0.392699,0.392699}

Verify...

a/2


0.392699

• Thanks! this is very straightforward.
– user51833
Jun 17, 2021 at 4:39