Rcpp程序中的min和max函数

6

我正在将一个 R 函数转换成 Rcpp 函数。一切都很好,但是我在使用标准的 max 和 min 函数时遇到了困难。以下是代码:

#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;
}

返回错误“没有匹配的函数调用min(int,&double)”。如果可能,我想使用std ::库min函数。

1个回答

14

只需将 std::min(1,temp) 更改为 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;
}

我假设这与std::min的模板定义有关。
template <class T> const T& min (const T& a, const T& b);

这段代码中定义的类型是单一类型(T),而你却传入了两种数据类型(intdouble)。

或者,由于你只是在比较两个值,可以用三元运算符(?:)来更加简洁地替换std::min

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

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

我猜测对于operator<,类型推断比std::min更加灵活。 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;
}

尽管在这种情况下,将1更改为1.0比(不必要地)定义int z再将其转换为双精度浮点数更容易,但您可以通过阅读函数/类定义(与大多数编程语言一样)学到很多东西。- cplusplus.comcppreference.com 是相当标准的来源 - 这通常会使编译器错误看起来不那么神秘。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接