简体   繁体   English

R和C ++中的Gibbs采样

[英]Gibbs Sampling in R and C++

I have checked gibbs sampling in different programming languages; 我用不同的编程语言检查过吉布斯抽样; in R 在R中

  x <- rgamma(1,3,y*y+4)
  y <- rnorm(1,1/(x+1),1/sqrt(2*(x+1)))

in c++ 在C ++中

  x = R::rgamma(3.0,1.0/(y*y+4));
  y = R::rnorm(1.0/(x+1),1.0/sqrt(2*x+2));

If it uses R functions why it differs in c++ as rgamma takes no n=number of observation and it takes scale instead of rate as default input and rnorm has no n= number of observation as well. 如果它使用R函数,为什么它在c ++中会有所不同,因为rgamma不接受n =观察次数,并且取小数位数而不是速率作为默认输入,并且rmrm也没有n =观察次数。

For Rcpp it is totaly different such as; 对于Rcpp,完全不同,例如;

 y = ::Rf_rnorm(1.0/(x+1),1.0/sqrt(2*x+2));

What's your question? 你有什么问题?

R::rgamma() is from Rcpp too. R::rgamma()也来自Rcpp。 It conveniently wraps the C-level, non-namespaced ::Rf_rnorm() . 它方便地包装C级,非命名空间的::Rf_rnorm()

Note that you also have the vectorised Rcpp::rnorm() -- and that there are plenty of Gibbs Sampler examples out there following the initial post by Darren Wilkinson. 请注意,您还具有矢量化的 Rcpp::rnorm() ,在达伦·威尔金森(Darren Wilkinson)发表第一篇文章之后,还有很多吉布斯采样器(Gibbs Sampler)示例。 Our best example may be this page at the Rcpp Gallery . 最好的例子可能是Rcpp Gallery上的此页面

Edit: And as you are evidently confused over the shape = 1/rate parameterization, here is a complete and worked example for you: 编辑:并且您显然对shape = 1/rate参数化感到困惑,这是一个完整而有效的示例:

We compile a convenience R function calling C++ via Rcpp first: 我们首先编译一个通过Rcpp调用C ++的便捷R函数:

R> cppFunction("NumericVector callrgamma(int n, double shape, double scale) { 
+                  return(rgamma(n, shape, scale)); }")
R>

We then call R, making sure we fix the seed: 然后我们调用R,确保我们修复了种子:

R> set.seed(42); rgamma(3, 2.0, 2.0)   # calling R
[1] 1.824478 0.444055 0.779610
R>

Now, using the same seed , we call the C++ function and we make sure we respect the "1/over" reparameterization as well: 现在,使用相同的种子 ,我们调用C ++函数,并确保我们也尊重“ 1 / over”重新参数化

R> set.seed(42); callrgamma(3, 2.0, 1/2.0)   # calling Rcpp
[1] 1.824478 0.444055 0.779610
R> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM