在Rcpp(和RcppArmadillo)中,如何检查vec是否包含复数

In Rcpp (and RcppArmadillo), how to check if a vec contains complex numbers?

本文关键字:vec 检查 是否 包含复 何检查 Rcpp RcppArmadillo      更新时间:2023-10-16

在R中,我们可以使用is.complex(例如is.complex(vec1)(来检查向量(例如,vec1=c(1+1i,2)(是否包含复数。我想知道RcppArmadillo中的等效函数是什么?

如何提取RcppArmadillo中向量中每个元素的实部,就像R中的Re(vec1)一样?

为了提取实部和虚部,可以使用arma::real()arma::imag()函数。或者,您可以使用糖函数Rcpp::Re()Rcpp::Im():

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
// [[Rcpp::export]]
arma::vec getRe(arma::cx_vec x) {
return arma::real(x);
}
// [[Rcpp::export]]
Rcpp::NumericVector getIm(Rcpp::ComplexVector x) {
return Rcpp::Im(x);
}
/*** R
set.seed(42)
N <- 5
vec <- complex(5, rnorm(5), rnorm(5))
t(getRe(vec))
#>            [,1]        [,2]      [,3]       [,4]       [,5]
#> [1,] -0.9390771 -0.04167943 0.8294135 -0.4393582 -0.3140354
Re(vec)
#> [1] -0.93907708 -0.04167943  0.82941349 -0.43935820 -0.31403543
getIm(vec)
#> [1] -2.1290236  2.5069224 -1.1273128  0.1660827  0.5767232
Im(vec)
#> [1] -2.1290236  2.5069224 -1.1273128  0.1660827  0.5767232
*/

如果你使用上面的getRe(arma::vec x),你会得到:

Warning message:
In getRe(vec) : imaginary parts discarded in coercion

你不能把复数放在一个不打算存储它们的对象中。这是C++作为强类型语言的结果。因此不需要is.complex()的类似物。

请参阅Armadillo文档以获取更多参考。