Custom rng function

Is it possible to create user-defined rng functions? From Stan manual, one can do it with existing _rng functions, but what about creating a new one? More specifically, I need a wiener_rng function, but it is not yet implemented in Stan.


You can build it as a user-defined function with the _rng suffix. You will need at least one _rng in it so you can generated randomness, like uniform_rng for example. Otherwise the output from your function will always be the same.

I see. Thanks! But then when I sample from a wiener distribution within the custom rng function, how do I pass the randomness to it? Is there an example for a used-defined function that mirrors normal_rng? This could give me hits how to implement a user-defined wiener_rng.

Do these examples help : 18.4 Functions acting as random number generators | Stan User’s Guide

I saw them, thanks! But at the end, they all use an existing _rng function to generate the needed random draws, so it is still unclear how to actually implement this process within a user-defined function.

There is a more complex example on page 24 in this tutorial: (also available at

1 Like

ok, thanks! This is a very nice example! But my conclusion is that I will have to do the wiener random sampling outside of Stan.

Looking at the code that the RWiener package uses on GitHub, the rng for the wiener distribution uses a uniform random variable and rejection sampling. It would be some work, but it looks like you could translate that to Stan code that uses the uniform_rng() function.


Just to complement, rejection sampling can be implemented in pure Stan, e.g. Sampling from truncated lognormal - #2 by bbbales2


That’s a great pointer, thanks! Just to make sure - does it also involve r_random_walk ? I didn’t see where it is being called in the rwiener.c.

1 Like