How to draw a random int from 0 to 100 in rstan?

Is there some function to make sure I can generate one random int from 0 to 100?

You can use categorical_rng:

int z = categorical_rng(rep_vector(1, 100));
1 Like

Your query reflects a common misunderstanding of what a Stan program is doing. Stan permits you to express a generative model structure using a variety of probability-related functions, but nothing in a Stan program is allowed to be stochastic by itself. The stochasticity for MCMC comes from the HMC sampler that gets bundled with your Stan program when it is compiled. The sampler will generate random guesses for every parameter then compute the log-probability density implied by these parameters, the data and the model structure manifest by the Stan program you’ve coded. The sampler then uses the final sum log probability density from every set of guesses to inform its parameter guessing strategy in a complicated way that eventually yields a history of guesses that reflect samples from the posterior.


Ah, yes, this is how you do it in the case of generated quantities (or transformed data I think).

1 Like

categorical_rng: Probabilities parameter is not a valid simplex. sum(Probabilities parameter) = 100, but should be 1 (in ‘model97c46e55466_method3_update’ at line 98)
It does not work

rep_vector (1,100) means generate size 100 vector consisting of copies of 0. It is not from 0 to 100

Copies of 1, not 0. You can turn this into a 'simplex` by dividing by 100:

int z = categorical_rng(rep_vector((1.0 / 100), 100));

Thank you very much. It does work now.