问题描述
考虑本RCPP犰狳功能:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace arma;
// [[Rcpp::export]]
vec testfun(const vec &x,const double &y,const double &z)
{
vec out = ((y < x) - z) % (x - y);
return out;
}
现在运行下述R脚本我得到不一致的结果:
Rcpp::sourceCpp("functions/test.cpp")
x <- 1:3
y <- 2
z <- 0.5
out_r <- ((y < x) - z) * (x - y)
out_cpp <- testfun(x,y,z)
print(out_r)
print(out_cpp)
[1] 0.5 0.0 0.5
[,1]
[1,] 0
[2,] 0
[3,] 1
所以不知何故比较失败。我会很高兴就如何解决这个问题的任何意见。来自R的到来,我认为一个环太复杂了这个任务。也许我错了。
解决方法
几个简短的声明:
- Armadillo C++ 矩阵线性代数库在向量到标量运算之外没有自动回收。
-
C++ 确实有更严格的类型控制,这使得从导致
unsigned int
的比较到带有double
的减法有问题。
第二部分才是真正的麻烦所在。为了说明这一点,我们将通过编写如下调试函数来系统地逐步执行每个操作:
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
using namespace arma;
// [[Rcpp::export]]
arma::vec debug_inline_statements(const vec &x,const double &y,const double &z)
{
// Isolate the problem statement:
// Ok
Rcpp::Rcout << "(x - y)" << std::endl << (x - y) << std::endl;
// Ok
Rcpp::Rcout << "1.0*(y < x):" << std::endl << 1.0*(y < x) << std::endl;
// Bad
Rcpp::Rcout << "(1.0*(y < x) - z):" << std::endl << ((1.0*(y < x)) - z) << std::endl;
// What went wrong? Conversion from Unsigned integer to double.
// Solution: Help the template expansion:
vec bool_to_double = arma::conv_to<arma::vec>::from(y < x);
Rcpp::Rcout << "(double(y < x) - z):" << std::endl << (bool_to_double - z) << std::endl;
// Success!
// All together now:
Rcpp::Rcout << "(double(y < x) - z) % (x - y):" << std::endl <<
(arma::conv_to<arma::vec>::from(y < x) - z) % (x - y) << std::endl;
return (arma::conv_to<arma::vec>::from(y < x) - z) % (x - y);
}
运行函数给出:
x <- 1:3
y <- 2
z <- 0.5
out_cpp <- debug_inline_statements(x,y,z)
# (x - y)
# -1.0000
# 0
# 1.0000
#
# 1.0*(y < x):
# 0
# 0
# 1
#
# (1.0*(y < x) - z):
# 0
# 0
# 1
#
# (double(y < x) - z):
# -0.5000
# -0.5000
# 0.5000
#
# (double(y < x) - z) % (x - y):
# 0.5000
# 0
# 0.5000
输出与预期不符:
(1.0*(y < x) - z)
通过显式类型转换,从 uvec
到 vec
,计算再次可行:
(arma::conv_to<arma::vec>::from(y < x) - z)
注意,显式转换请求是通过 arma::conv_to<>::from()
在计算的向量部分完成的。