Rcpp:如何将复数从 R 传递到 cpp
Rcpp: how to pass complex number from R to cpp
我想使用 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 中的向量,标量 "really" 不存在:它们是长度为 1 的向量。因此,对于单个 complex
数字,您(仍然)传递一个 ComplexVector
恰好长度为 1。
查看 Baptiste 的两个软件包,它们通过 RcppArmadillo 进行复杂的数学计算——"proves" 某些 RcppArmadillo 接口按其应有的方式工作。
编辑: 如果您真的想要一个标量,您也可以得到它:
R> cppFunction("std::complex<double> doubleMeScalar(std::complex<double> x) {
+ return x+x; }")
R> doubleMeScalar(1+1i)
[1] 2+2i
R>
我想使用 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 中的向量,标量 "really" 不存在:它们是长度为 1 的向量。因此,对于单个 complex
数字,您(仍然)传递一个 ComplexVector
恰好长度为 1。
查看 Baptiste 的两个软件包,它们通过 RcppArmadillo 进行复杂的数学计算——"proves" 某些 RcppArmadillo 接口按其应有的方式工作。
编辑: 如果您真的想要一个标量,您也可以得到它:
R> cppFunction("std::complex<double> doubleMeScalar(std::complex<double> x) {
+ return x+x; }")
R> doubleMeScalar(1+1i)
[1] 2+2i
R>