# [R] generating a gamma random variable

Faheem Mitha faheem at email.unc.edu
Sun Oct 21 17:22:53 CEST 2001


On Sun, 21 Oct 2001, Bob O'Hara wrote:

> Faheem Mitha wrote:
> >
> > Dear R People,
> >
> > This question has nothing to do with R directly, but it is a simulation
> > question. I need to generate a random variable distributed as
> > gamma(\alpha,\beta), with the additional proviso that it must be a
> > function of random variable(s) which do not depend on \alpha, \beta. In
> > this case, I have \alpha = (T-1)/2, where T is a positive integer.
> >
> > So, it seems reasonable to first simulate from a chi-squared distribution
> > with T-1 degrees of freedom. Then multiply by the appropriate scale
> > factor.
> >
> Is there a reason why you don't want to use either rgamma or rchisq?

Come to think of it, there is no reason why I should not use rchisq. This
would depend on T, but that is Ok, since T is a constant within the
calculation, and the method I'm using above depends on T being fixed
anyway. This would probably be the most efficient way, since to get a
gamma distribution would then just involve multiplying by a constant.

Background: I'm using this simulation to run coupled Markov chains. T is a
contant within the calculation.

> > There seem to be at least two different ways to simulate from a
> > chi-squared distribution with n degrees of freedom.
> >
> There are much quicker ways than you suggested.  A rejection algorithm
> is one choice.  I'll save him the embarrassment of having to indulge in
> self promotion by suggesting that the classic text is Brian Ripley's
> 1987 book 'Stochastic Simulation'. There is also an algorithm in Press
> et al.'s 'Numerical Recipes in C'.

Yes, actually Stochastic Simulation is on my desk as I write, and it
suggests the methods I outlined above for simulating from chisq/gamma.

I'm still wondering about how to check (in general) whether a bunch of rvs
are distributed as gamma or not. How do people check such things in
practice?