在R和C ++中的Gibbs采样 [英] Gibbs Sampling in R and C++
问题描述
我已经检查过不同编程语言的吉布斯抽样; in R
I have checked gibbs sampling in different programming languages; in R
x <- rgamma(1,3,y*y+4)
y <- rnorm(1,1/(x+1),1/sqrt(2*(x+1)))
in c ++
x = R::rgamma(3.0,1.0/(y*y+4));
y = R::rnorm(1.0/(x+1),1.0/sqrt(2*x+2));
如果它使用R函数为什么它在c ++中不同,因为rgamma不需要n =观察次数,采用scale而不是rate作为默认输入,rnorm没有n =观察数。
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.
对于Rcpp,它是完全不同的,如:
For Rcpp it is totaly different such as;
y = ::Rf_rnorm(1.0/(x+1),1.0/sqrt(2*x+2));
推荐答案
R :: rgamma()
也来自Rcpp。它方便地包装C级非命名空间 :: Rf_rnorm()
。
R::rgamma()
is from Rcpp too. It conveniently wraps the C-level, non-namespaced ::Rf_rnorm()
.
注意, Rcpp :: rnorm()
- 并且有很多Gibbs采样器示例,在Darren Wilkinson的初始发布之后。我们最好的例子可能是 Rcpp画廊的此页。
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. Our best example may be this page at the Rcpp Gallery.
编辑:由于您对 shape = 1 / rate
参数化显然感到困惑,并为您工作的示例:
And as you are evidently confused over the shape = 1/rate
parameterization, here is a complete and worked example for you:
我们编译一个方便的R函数通过Rcpp调用C ++:
We compile a convenience R function calling C++ via Rcpp first:
R> cppFunction("NumericVector callrgamma(int n, double shape, double scale) {
+ return(rgamma(n, shape, scale)); }")
R>
然后我们调用R,确保修复种子:
We then call R, making sure we fix the seed:
R> set.seed(42); rgamma(3, 2.0, 2.0) # calling R
[1] 1.824478 0.444055 0.779610
R>
现在,使用相同的种子,我们调用C ++函数我们确保我们尊重1 / over重新参数化:
Now, using the same seed, we call the C++ function and we make sure we respect the "1/over" reparameterization as well:
R> set.seed(42); callrgamma(3, 2.0, 1/2.0) # calling Rcpp
[1] 1.824478 0.444055 0.779610
R>
这篇关于在R和C ++中的Gibbs采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!