Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building R package: "Found 'rand', possibly from 'rand' (C)" NOTE when checking package

Tags:

c++

r

rcpp

cran

I am building an R package that contains C++ code. Among others, I use the rand() function. The package checks and builds without any irregularities on my Linux machine. However, when I attempt to check the Windows build using the Windows builder, I am getting the following warning:

* checking compiled code ... NOTE
File 'tagcloud/libs/i386/tagcloud.dll':
  Found 'rand', possibly from 'rand' (C)
    Object: 'overlap.o'
  Found 'srand', possibly from 'srand' (C)
    Object: 'overlap.o'
File 'tagcloud/libs/x64/tagcloud.dll':
  Found 'rand', possibly from 'rand' (C)
    Object: 'overlap.o'
  Found 'srand', possibly from 'srand' (C)
    Object: 'overlap.o'

Compiled code should not call entry points which might terminate R nor
write to stdout/stderr instead of to the console, nor the C RNG.

Here is some example code:

#include "Rcpp.h"
#include <cstdlib>
#include <time.h>

using namespace Rcpp;

RcppExport SEXP test(  ) {
  double x ;
  srand( (unsigned) time(NULL) );
  x = rand();
  return( 1 );
}

I don't understand the complaints about rand(). I also don't see where in the code I "call entry points which might terminate R" or "write to stdout/stderr", but then, if I remove the calls to rand/srand, this message disappears.

Google shows a lot of packages that seem to have the same NOTE in their check logs. Have you seen it? Is there a way I can get rid of it?

like image 910
January Avatar asked Sep 30 '22 12:09

January


1 Answers

The discussion in the comments already hits the essential point: R (as of late) complains about use of rand() and srand(). [ Note that that is an R issue, not an Rcpp issue. ]

The reasoning is that at some points in the past, rand() was really bad on some systems. So warnings persist. See eg from this page at cppreference.com:

There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls).

rand() is not recommended for serious random-number generation needs, like cryptography. It is recommended to use C++11's random number generation facilities to replace rand(). (since C++11)

In the case of an R, and Rcpp package, you have no reason whatsoever to rely on rand() as R comes with several high-quality generators. Please see the Writing R Extension manual how to access them from C code, and the numerous Rcpp examples (here, Rcpp documtation, Rcpp Gallery) on how to access them from C++ via Rcpp.

like image 66
Dirk Eddelbuettel Avatar answered Oct 02 '22 14:10

Dirk Eddelbuettel