vectorized exponent for pow in Rcpp

大憨熊 提交于 2020-12-11 10:08:17

问题


Rcpp allows to vectorize some operations, which is great. But for pow only the base number can be a vector, not the exponent. Typically, on compilation:

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector puissancedCpp(NumericVector base, double exp){
    return pow(base,exp);
}

works but not:

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector puissancedCpp(NumericVector base, NumericVector exp){
    return pow(base,exp);
}

What would be the recommended way to perform what in R would be:

c(0,1,2,3)^c(4,3,2,1) 

in the middle of other things done in C?


回答1:


Here's one option, assuming your compiler supports C++11:

#include <Rcpp.h>
// [[Rcpp::plugins(cpp11)]]

// [[Rcpp::export]]
std::vector<double> vpow(const std::vector<double>& base, const std::vector<double>& exp) {
    std::vector<double> res(base.size());
    std::transform(base.begin(), base.end(), exp.begin(), res.begin(),
                  [&](double lhs, double rhs) -> double {
                    return std::pow(lhs, rhs);
                  });
    return res;
}


/*** R

c(0,1,2,3)^c(4,3,2,1) 
#[1] 0 1 4 3
vpow(0:3, c(4,3,2,1))
#[1] 0 1 4 3

*/

If you're working with an older compiler, you could achieve this using

double dpow(const double lhs, const double rhs) {
  return std::pow(lhs, rhs);
}

// [[Rcpp::export]]
std::vector<double> vpow98(const std::vector<double>& base, const std::vector<double>& exp) {
    std::vector<double> res(base.size());
    std::transform(base.begin(), base.end(), exp.begin(), res.begin(), dpow);
    return res;
}



回答2:


An alternative if you for some reason can't use C++11

#include <Rcpp.h>

using namespace Rcpp;  

// [[Rcpp::export]]
NumericVector vecpow(const NumericVector base, const NumericVector exp) {
  NumericVector out(base.size());
  std::transform(base.begin(), base.end(),
                 exp.begin(), out.begin(), ::pow);
  return out;
}

/*** R
vecpow(c(0:3), c(4:1))
***/

which produces

R> Rcpp::sourceCpp("vecpow.cpp")

R> vecpow(c(0:3), c(4:1))
[1] 0 1 4 3
R> 


来源:https://stackoverflow.com/questions/30106492/vectorized-exponent-for-pow-in-rcpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!