0

I guess the function gamma only works for a vector as the input. Is there a way to apply it to a scalar, say,gamma(3)`?

Actually, I would get the correct output if I include gamma(3) as part of my code, but there's a warning message....

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List fool(NumericVector vec){
  double res = 0;
  res = sum(gamma(vec)) + gamma(3);
  List result;result["num"] = res;
   return result;
}

Here is the warning messgae:

exp.cpp:7:27: warning: 'gamma' is deprecated: first deprecated in OS X 10.9 [-Wdeprecated-declarations]
res = sum(gamma(vec)) + gamma(3);
^ /usr/include/math.h:720:15: note: 'gamma' has been explicitly marked deprecated here extern double gamma(double) __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0, __MAC_10_9, __IPHONE_NA, __IPHONE_NA); ^ 1 warning generated.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • 2
    The warning message comes from elsewhere in your code, because `3` is a vector and `gamma(3)` returns `2`, as expected. – Rui Barradas Apr 16 '18 at 18:58
  • Please show the code, and the warning message. See [how to make a great reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for helpful suggestions. – Dirk Eddelbuettel Apr 16 '18 at 22:32
  • Sorry for being unclear. I've attached my code here:) – lostintheforest Apr 17 '18 at 00:13

1 Answers1

2

Thanks for posting code. You fell victim of being careless with namespaces. There is a (vectorized) gamma() in the Rcpp namespace -- the first argument and there is (was) a scalar gamma() (preferred: tgamma()) in the C math library. And it is better to be explicit.

Corrected code below:

#include <Rcpp.h>

// [[Rcpp::export]]
double fool(Rcpp::NumericVector vec){
    double res =
        Rcpp::sum(Rcpp::gamma(vec)) +   // Rcpp sugar sum() and gamma() on vector
        ::tgamma(3.0);                  // math library tgamma of double
    return res;
}

/*** R
v <- 1:5
fool(v)
sum(gamma(v)) + gamma(3)
*/

Output

R> sourceCpp("/tmp/shuang.cpp")

R> v <- 1:5

R> fool(v)
[1] 36

R> sum(gamma(v)) + gamma(3)
[1] 36
R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725