簡體   English   中英

為什么這兩個函數給出不同的結果?

[英]Why do the two functions give different results?

我使用RcppArmadillo包定義了兩個函數並將它們保存到文件cxxFuns.cpp f01f02之間的唯一區別是V(0, 0)

#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
arma::mat f01 (arma::mat x) {
    unsigned int p0 = x.n_cols ;
    unsigned int iR = 0, iC = 0 ;
    arma::mat V(3, 3) ; V.fill(NA_REAL) ;
    for (iR = 0; iR < p0; iR++) { 
        V(0, 0) = arma::sum(x.col(iR) % x.col(iR)) ;
        for (iC = iR+1; iC < p0; iC++) {
            ;
        }
    }
    
    return V ;
}

// [[Rcpp::export]]
arma::mat f02 (arma::mat x) {
    unsigned int p0 = x.n_cols ;
    unsigned int iR = 0, iC = 0 ;
    arma::mat V(3, 3) ; V.fill(NA_REAL) ;
    for (iR = 0; iR < p0; iR++) { 
        for (iC = iR+1; iC < p0; iC++) {
            V(0, 0) = arma::sum(x.col(iR) % x.col(iR)) ;
        }
    }
    
    return V ;
}

據我了解,函數f01f02應該給出相同的結果。 但是,測試並未顯示預期結果。

rm(list=ls())
set.seed(2020)
Rcpp::sourceCpp('cxxFuns.cpp')
x <- matrix(rnorm(100*10), 10)
(egg01 <- f01(x))
         [,1] [,2] [,3]
[1,] 12.78607   NA   NA
[2,]       NA   NA   NA
[3,]       NA   NA   NA

(egg02 <- f02(x))
         [,1] [,2] [,3]
[1,] 14.80855   NA   NA
[2,]       NA   NA   NA
[3,]       NA   NA   NA

發生了什么?

第一個塊中的最后一次執行是在iR = p0-1

第二個塊中的最后一次執行是在iC=p0-1
由於iCiR+1開始,您最后一次執行是針對iR=p0-2

在計算V(0,0)或在調試器下運行之前打印iR的值應該立即清楚這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM