Consider the following code:

sampling = 
 Compile[{{T, _Real}, {nparticles, _Integer}}, 
  RandomVariate[GammaDistribution[3, T], nparticles], 
  CompilationTarget -> "C"]

It will be a part of another compiled code, so it is crucial for me to keep everything compiled. However, it calls MainEvaluate, probably because GammaDistribution is not compilable. Is there a workaround here?


1 Answer 1


Is UniformDistribution compilable? (Or maybe RandomReal?) If so, then making use of the fact that a Gamma[3, t] has the same distribution as a sum of 3 Exponential random variables with parameter $t$ might help:

nparticles = 1000000;
t = 4.5;
x = -t  Total[Log[#]] & /@ RandomVariate[UniformDistribution[{0, 1}], {n, 3}];
Show[Histogram[x, "FreedmanDiaconis", "PDF"],
 Plot[PDF[GammaDistribution[3, t], z], {z, 0, 50}]]

PDF of gamma distribution and histogram of a random sample from that distribution


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.