Rstan expose_stan_functions and random seed

I 'm trying to debug some code by matching outputs from exposed stan and r functions. And as this involves generating a random number, I’m trying to set the random seed before calling each function.

A toy example - given attached stan file:
mvrnorm_rng.stan (263 Bytes)

I’d like vec1 and vec 2 in this R code to match:

library(rstan)
expose_stan_functions(stanc(file = "mvrnorm_rng.stan"))


mu <- c(0, 0, 0)
sigma <- matrix(c(10,3,3,2,),2,2)

set.seed(54)
vec1 <- MASS::mvrnorm(1, mu, sigma)
set.seed(54)
vec2 <- mvrnorm_rng(mu, sigma)
> vec1
[1] -5.770811 -2.444942
> vec2
[1] -3.0136115 -0.5758493

So how do I set the same seed for the c++ stan function?
Thanks.

The example in the RStan docs appears to cover this, but I can’t check that it works as described currently:

1 Like

Yes I have tried adopting that code, but it’s not working for me (assuming I don’t have an error somewhere).

 mu <- c(0, 0)
> sigma <- matrix(c(10,3,3,2),2,2)
> set.seed(54)
> vec1 <- MASS::mvrnorm(1, mu, sigma)
> PRNG <- get_rng(seed = 54)
> o <- get_stream()
> vec2 <- mvrnorm_rng(mu, sigma, base_rng__ = PRNG, pstream = )
> vec1
[1] -5.770811 -2.444942
> vec2
[1] -0.2808614 -0.6238547

Edit: I’m on rstan_2.32.6 and StanHeaders_2.32.5

but the Stan mvnorm_rng and the MASS implementation are almost for sure different - they will never give you the same… and in addition, the random number generator is also different to my memory.

Otherwise - the rstan bits are ok.

1 Like

A given seed won’t necessarily provide the same draw between two different implementations

1 Like

Ah. Ok thanks for your help, I didn’t realise that.