user-2147482565
user-2147482565

Reputation: 463

Getting NaN when using R::runif in Rcpp

To generate standard uniform random numbers with Rcpp, I always used

Rcpp::runif(1, 0, 1)[0]

The [0] is due to Rcpp::runif returning vectors. I recently found that you can also use the R API and use R::runif() instead if you only want a scalar so I can avoid using this [0]. I tried this out, but I always get nan's. Here is a small example, the .cpp file:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double unif_R() {
  const double u = R::runif(1, 0);
  Rcout << "u: " << u << "\n";
  return u;
}

// [[Rcpp::export]]
double unif_Rcpp() {
  const double u = Rcpp::runif(1, 0, 1)[0];
  Rcout << "u: " << u << "\n";
  return u;
}

The unif_R() function uses R::runif(a,b) that returns a scalar, while unif_Rcpp() uses Rcpp::runif(n, a, b), which returns a vector. However, when I call these in R using:

sourceCpp('runif_test.cpp')
set.seed(21)
unif_R()

set.seed(21)
unif_Rcpp()

set.seed(21)
runif(1)

I get the following output:

> set.seed(21)
> unif_R()
u: nan
[1] NaN
> set.seed(21)
> unif_Rcpp()
u: 0.786115
[1] 0.7861149
> set.seed(21)
> runif(1)
[1] 0.7861149

Clearly unif_Rcpp\ works, but why does unif_R\ give me nan's?

Upvotes: 0

Views: 142

Answers (1)

user-2147482565
user-2147482565

Reputation: 463

As noted by @user20650, I made a silly mistake and that I need b >= a. So the correct code should've been:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double unif_R() {
  const double u = R::runif(0, 1);
  Rcout << "u: " << u << "\n";
  return u;
}

// [[Rcpp::export]]
double unif_Rcpp() {
  const double u = Rcpp::runif(1, 0, 1)[0];
  Rcout << "u: " << u << "\n";
  return u;
}

And this is fine.

Upvotes: 3

Related Questions