Can I use inverse-cdf-type method to simulate from custom integer distributions?

Hi, I am wondering if I am doing this right all along. For simplicity, suppose I am working with the Geometric distribution, which does not have a built-in Stan rng. Can I do this?

real geometric_rng( real theta) {
  real u = uniform_rng(0,1);
  real x = floor ( log(1-u)/log(1-theta) );
  return x;

Honestly, my experience suggests this seems ok. But I’d love to know if there is a proper way to do this, assuming there is a closed-form expression for the inverse-CMF (cumulative mass function)?

Yes, that is fine. Use the built-in functions log1m() for better accuracy near 1.

I know you’re just using the geometric distribution as an example but you can use the negative binomial _rng function for it.

1 Like