สุ่มเลขใน Stan

มีคนถามมาว่าจะรันสุ่มเลขจาก distribution แบบไม่ต้องมีพารามิเตอร์หรือใส่ค่าให้พารามิเตอร์ให้กับ distribution ไปเลยทำยังไงใน Stan

ตัวอย่างcodeนะครับ

### test.stan ##
data {
 real a;
 real b;
 real ab;
 real bb;
}
generated quantities{
  real gm;
  real bt;
  gm = gamma_rng(a,1/b);
  bt = beta_rng(ab,bb);
}



### run the stan code in R
library(cmdstanr)
library(bayesplot)       
library(patchwork)

# the parameters of the distributions are given as the data
data_list <- list(a=1.5,b=0.001,ab=15,bb=1)

#compile the model
mod <- cmdstan_model(test.stan)

#do the sampling
fit <- mod$sample(data = data_list,chains = 1,fixed_param = T)

# draw the histograms
mcmc_hist(fit$draws(c("gm","bt")))

Leave a Reply

%d bloggers like this: