[R] R equivilant to RAND_MAX in C

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Mar 23 08:40:04 CET 2004

On Mon, 22 Mar 2004, Rajarshi Guha wrote:

> Hello,
>   I have some C code that I'm interfacing to R using the .C calling
> interface. Currently the C code uses the rand() function from the GNU C
> library to generate random numbers. Since I need the random numbers in a
> range from 0 to a (where a is an integer) I use the RAND_MAX macro as
> (int)(rand() * (float)(*nobs-1) / (RAND_MAX+1.0))
> (taken from the rand() manpage)

That isn't a random *number*: it is a random *integer*.  It is a random 
integer on 0, ..., a=*nobs-2: is that what you wanted?

> However, since I have access to the R RNG's I'd like to use them.
> Firstly, would it be an improvement to use the R RNG over that supplied
> by the C library?

Most likely.

> Secondly, I dont see any mention of an equivilant to RAND_MAX in the
> documentation of runif() (as I want to use unif_rand() in my C code).

That's because runif() is documented to return a *double*, and unif_rand() 
a uniform(0,1) *double*. This is in `Writing R Extensions'.

> Is it valid to use the C libraries' RAND_MAX as the maximum value of the
> RNG or am I missing something?

That the C rand() is *integer*.

> As far as I understand using the .C interface I can't call R functions
> from my C code (which means I cant access runif()) - is this correct?
> As I would rather stay with the .C interface rather than the .Call
> interface is there a way to get random numbers within a given range?

a + (b-a) * unif_rand()  for U(a, b)

(int) (a * unif_rand()) for a random integer in 0, ... , a - 1.

Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

More information about the R-help mailing list