Min and max in Rcpp programs

I converted an R function to an Rcpp function. It's ok, but I find it difficult to use the standard max and min function. Code below:

#include <math.h>
#include <RcppArmadillo.h>
#include <algorithm>
#include <iostream>

// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using namespace arma;
using namespace std;

double f4RandomC(double x, double a, double b) {
  double out, temp;

  temp=(log( (a*(1-x)) / (a+x) )) /log(b) ;
  out= std::min(1,temp );
  return out;
}

      

returns me the error "no matchinf function to call min (int, & double). If possible, I would like to use the std :: library min function

+3


source to share


1 answer


Just change std::min(1,temp)

to std::min(1.0,temp)

:

#include <cmath>
#include <Rcpp.h>
// [[Rcpp::export]]
double f4RandomC(double x, double a, double b) {
  double out, temp;

  temp =(log( (a*(1-x)) / (a+x) )) /log(b) ;
  out = std::min(1.0,temp );
  return out;
}

      

I guess it has to do with defining the template std::min

template <class T> const T& min (const T& a, const T& b);

      

which is only defined by one T

data type ( ), whereas you were passing two data types ( int

and double

) to it.

Or, since you are only comparing two values, you can do it a little more concisely by replacing it std::min

with the ternary operator ( ?:

):



double f4RandomC(double x, double a, double b) {
  double temp;

  temp =(log( (a*(1-x)) / (a+x) )) /log(b) ;
  return temp < 1 ? temp : 1;
}

      

I guess type deduction is a little more flexible for operator<

than std::min

.

Two other options with std::min

:

// [[Rcpp::export]]
double f4RandomC2(double x, double a, double b) {
  double out, temp;
  int z = 1;
  temp =(log( (a*(1-x)) / (a+x) )) /log(b) ;
  out = std::min( static_cast<double>(z),temp );
  return out;
}

// [[Rcpp::export]]
double f4RandomC3(double x, double a, double b) {
  double out, temp;
  int z = 1;
  temp =(log( (a*(1-x)) / (a+x) )) /log(b) ;
  out = std::min<double>( z,temp );
  return out;
}

      

Although in this case it is much easier to just change 1

to 1.0

than (optionally) define int z

it to just send it to a double later on.

You can learn a lot by reading function / class definitions (as in most programming languages) - cplusplus.com and cppreference.com are pretty standard sources - and this often makes compiler errors seem less cryptic.

+8


source







All Articles