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));
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.
For Rcpp it is totaly different such as;
y = ::Rf_rnorm(1.0/(x+1),1.0/sqrt(2*x+2));
What's your question?
R::rgamma()
is from Rcpp too. It conveniently wraps the C-level, non-namespaced ::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. Our best example may be this page at the Rcpp Gallery .
Edit: And as you are evidently confused over the shape = 1/rate
parameterization, here is a complete and worked example for you:
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>
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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.