C++ 当算法放在循环中时,它会产生不同的结果,C++;
我在Rcpp中创建了以下算法,并在R中编译它C++ 当算法放在循环中时,它会产生不同的结果,C++;,c++,r,algorithm,rcpp,C++,R,Algorithm,Rcpp,我在Rcpp中创建了以下算法,并在R中编译它 // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadilloExtensions/sample.h> // [[Rcpp::export]] arma::colvec Demo(arma::mat n, int K){ arma::colvec N(K); for(int j=0; j<K; ++j){ for(int i=0; i<(K
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::export]]
arma::colvec Demo(arma::mat n, int K){
arma::colvec N(K);
for(int j=0; j<K; ++j){
for(int i=0; i<(K-j); ++i){
N[j] += accu(n.submat(i,0,i,j));
}
}
return N;
}
/***R
K = 4
n = cbind(c(1008, 5112, 1026, 25, 0), 0, 0, 0, 0)
Demo(n,K)
for(i in 1:3){
print(Demo(n,K))
print(K)
print(n)
}
*/
然后,如果我运行算法Demo
一次,我就会收到正确的结果
> Demo(n,K)
[,1]
[1,] 7171
[2,] 7146
[3,] 6120
[4,] 1008
然而,如果我在一个循环中多次运行它,它的行为就会开始变得怪异
for(i in 1:3){
print(Demo(n,K))
print(K)
print(n)
}
[,1]
[1,] 7171
[2,] 7146
[3,] 6120
[4,] 1008
[1] 4
[,1] [,2] [,3] [,4] [,5]
[1,] 1008 0 0 0 0
[2,] 5112 0 0 0 0
[3,] 1026 0 0 0 0
[4,] 25 0 0 0 0
[5,] 0 0 0 0 0
[,1]
[1,] 14342
[2,] 14292
[3,] 12240
[4,] 2016
[1] 4
[,1] [,2] [,3] [,4] [,5]
[1,] 1008 0 0 0 0
[2,] 5112 0 0 0 0
[3,] 1026 0 0 0 0
[4,] 25 0 0 0 0
[5,] 0 0 0 0 0
[,1]
[1,] 21513
[2,] 21438
[3,] 18360
[4,] 3024
[1] 4
[,1] [,2] [,3] [,4] [,5]
[1,] 1008 0 0 0 0
[2,] 5112 0 0 0 0
[3,] 1026 0 0 0 0
[4,] 25 0 0 0 0
[5,] 0 0 0 0 0
在第一次运行中,它正确地计算它,然后在第二次运行中,它给出正确的输出乘以2,在第三次运行中,它给出正确的输出乘以3。但是基于算法步骤,我没有看到产生这种行为的明显步骤
正确的输出应该是
for(i in 1:3){
print(Demo(n,K))
}
[,1]
[1,] 7171
[2,] 7146
[3,] 6120
[4,] 1008
[,1]
[1,] 7171
[2,] 7146
[3,] 6120
[4,] 1008
[,1]
[1,] 7171
[2,] 7146
[3,] 6120
[4,] 1008
您通过
+=
就地递增N
函数无法确保初始化为零<默认情况下,code>Rcpp倾向于这样做(我认为这是谨慎的做法)——但如果您知道您正在这样做,那么这可以被抑制以提高速度
下面是代码的最低修复版本(具有正确的标题,并调用.fill(0)
)
/[[Rcpp::depends(RcppArmadillo)]]
#包括
//[[Rcpp::导出]]
arma::colvec演示(arma::mat n,int K){
arma::colvec N(K);
N.fill(0);//重要,或构造为N(k,arma::fill::zeros)
对于(int j=0;j什么是accu
函数?你也可以在循环的每次迭代中打印n
并显示结果吗?它可能是arma::accu
的来源。还有,什么是IndAvel
?你刚刚重命名了Demo
还是另一个函数?a会有帮助。@DanM.accu
就像是和
一样>Dirk Eddelbuettel所说的Armadillo函数。是的,我还将打印矩阵n
。嗨,Dirk;只是出于好奇。在操作代码中,为什么运行Demo(n,K);Demo(n,K);Demo(n,K)
会给出预期的结果,但在循环中为(I In 1:3){print(Demo(n,K))}
,或者实际上{Demo(n,K);Demo(n,K);Demo(n,K)}给出奇怪的结果?在支撑中有什么东西在C++函数环境中保留什么东西吗?这是他在添加到未清除内存中的所有未确定的行为。只是未确定的输出如何在设置中变化。但这与底层代码有故障是不相关的。@ DrkdDelbuteltNIT:它是undefined@DanM是的,谢谢,更好的术语。不能再编辑评论了。
for(i in 1:3){
print(Demo(n,K))
}
[,1]
[1,] 7171
[2,] 7146
[3,] 6120
[4,] 1008
[,1]
[1,] 7171
[2,] 7146
[3,] 6120
[4,] 1008
[,1]
[1,] 7171
[2,] 7146
[3,] 6120
[4,] 1008
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
arma::colvec Demo(arma::mat n, int K){
arma::colvec N(K);
N.fill(0); // important, or construct as N(k, arma::fill::zeros)
for(int j=0; j<K; ++j){
for(int i=0; i<(K-j); ++i){
N[j] += accu(n.submat(i,0,i,j));
}
}
return N;
}
/***R
K = 4
n = cbind(c(1008, 5112, 1026, 25, 0), 0, 0, 0, 0)
Demo(n,K)
for(i in 1:3) {
print(Demo(n,K))
print(K)
print(n)
}
*/