【发布时间】:2018-05-16 17:28:27
【问题描述】:
我想在 Rcpp 中生成具有固定参数的二元正态分布样本 (Gibbs Sampler)。 R 中的代码非常简单,但由于我是 Rcpp 新手,因此我花了很多工作来调整代码。
我的 R 代码
gibbsR <- function(n,mu1,mu2,s1,s2,rho){
X <- numeric() ; Y <- numeric()
X[1] <- rnorm(1,mu1,s1) #init value for x_0
for(i in 1:n){
Y[i] <- rnorm(1,mu2+(s2/s1)*rho*(X[i]-mu1),sqrt((1-rho^2)*s2^2)) # Y|X
X[i+1] <- rnorm(1,mu1+(s1/s2)*rho*(Y[i]-mu2),sqrt((1-rho^2)*s1^2)) # X|Y
}
cbind(x=X[-1],y=Y)}
system.time(resR <- gibbsR(n=1000000,mu1=170,mu2=70,s1=10,s2=5,rho=0.8))
#colMeans(resR);apply(resR, 2, sd);cor(resR)
head(resR)
x y
[1,] 185.2425 79.27488
[2,] 178.0975 75.53521
[3,] 178.4902 74.29250
[4,] 173.7096 73.37504
[5,] 180.2141 72.89918
[6,] 171.0300 72.66280
我的 Rcpp 代码
library(Rcpp)
cppFunction("
NumericMatrix gibbsC(int n, double mu1, double mu2, double s1, double s2, double rho) {
NumericVector x; NumericVector y;
x[0] = Rf_rnorm(mu1,s1);
for(int i=0; i<n; i++){
y[i] = Rf_rnorm(mu2+(s2/s1)*rho*(x[i]-mu1),sqrt(1-pow(rho,2))*pow(s2,2)); // Y|X
x[i+1] = Rf_rnorm(mu1+(s1/s2)*rho*(y[i]-mu2),sqrt(1-pow(rho,2))*pow(s1,2)); // X|Y
}
return(cbind(x[-0],y));
}")
system.time(resC <- gibbsC(n=100000,mu1=170,mu2=70,s1=10,s2=5,rho=0.8))
#colMeans(resR);apply(resR, 2, sd);cor(resR)
head(resC)
知道如何获得类似于我的 gibbsR 函数的结果
【问题讨论】:
-
看看 Rcpp 库:gallery.rcpp.org/articles/gibbs-sampler
-
嗨,你能帮我看看这个问题stackoverflow.com/questions/65054971/…吗?谢谢。