Skip to contents

Packages can draw from zurand in C, into buffers they own and from their own worker threads, and get exactly the values the R functions return.

Setup

Declare LinkingTo: zurand and Imports: zurand in DESCRIPTION, then fetch the function table once, on the main thread:

#include <zurand.h>

const zurand_api *zr = zurand_get_api();     /* main thread, once */
zurand_key k;
zr->key_get(keys, 0, &k);                     /* keys: an rng_key from R */

/* then from any thread: */
if (zr->fill_normal(k, n, 0.0, 1.0, buf) != ZURAND_OK) { /* bad arguments */ }

The header, inst/include/zurand.h, documents the rest: uniform, integer and 64-bit fills, fill_normal_method() for rng_normal(method = "mcfarland"), and fold_int(), which derives a key exactly as rng_fold(key, i) does. Every function reports a bad argument with a return code, never an R error.

Long simulations

A long simulation need not hold its random numbers in memory at all. fill_normal_at(k, start, n, ...) fills any stretch of a key’s stream, so the caller can pull the next piece when it needs it. stream_normal() (and stream_uniform()) runs the loop for you, handing a callback one cache-sized chunk at a time through a buffer you own:

static int step(void *ctx, const double *x, size_t n, uint64_t start) {
    /* consume x[0 .. n-1], positions start .. start + n - 1 */
    return 0;                                  /* nonzero stops the stream */
}

double buf[16384];                             /* 128 KB: stays in cache */
zr->stream_normal(k, 1000000000, 0.0, 1.0, ZURAND_NORMAL_ZIGGURAT,
                  buf, 16384, step, &state);

The chunks are exactly rng_normal(k, 1e9), in order. From R, the same walk is rng_normal(key, n, offset = k).

Filling a reused buffer also saves the cost of a new R vector per call, which for large vectors is a large share of the time (see the performance article).