Rcpp:如何将复数从R传递到cpp

Rcpp: how to pass complex number from R to cpp

本文关键字:cpp Rcpp      更新时间:2023-10-16

我想使用Rcpp将复数从R传递到我的cpp代码。我尝试像传递双精度和整数一样传递复数:

#include <complex>
#include <Rcpp.h>
using namespace Rcpp;
RcppExport SEXP mandelC(SEXP s_c) {
    std::complex<double> c = ComplexVector(s_c)[0];
}

但是,代码无法编译并报错:

g++ -I/usr/share/R/include -DNDEBUG -I/usr/share/R/include -fopenmp  -I/home/siim/lib/R/Rcpp/include     -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c a.cpp -o a.o
a.cpp: In function ‘SEXPREC* mandelC(SEXP)’:
a.cpp:7:50: error: conversion from ‘Rcpp::traits::storage_type<15>::type {aka Rcomplex}’ to non-scalar type ‘std::complex<double>’ requested
std::complex<double> c = ComplexVector(s_c)[0];
                                              ^

显然,我做错了什么,但我一直找不到任何的例子。有人能给我指路吗?

你错过了一些非常简单的东西:

R> cppFunction("ComplexVector doubleMe(ComplexVector x) { return x+x; }")
R> doubleMe(1+1i)
[1] 2+2i
R> doubleMe(c(1+1i, 2+2i))
[1] 2+2i 4+4i
R> 

记住所有都是R中的向量,标量并不"真正"存在:它们是长度为1的向量。因此,对于单个complex数,您(仍然)传递长度为1的ComplexVector

看看Baptiste的两个包,它们通过RcppArmadillo进行复杂的数学运算——这"证明"了一些RcppArmadillo接口是按照它们应该的方式工作的。

编辑:如果你真的需要一个标量,你也可以得到它:

R> cppFunction("std::complex<double> doubleMeScalar(std::complex<double> x) { 
+                                                   return x+x; }")
R> doubleMeScalar(1+1i)
[1] 2+2i
R>