The Lumber Room

"Consign them to dust and damp by way of preserving them"

Poor man’s random number generators in C++

with 3 comments

There are random number libraries, Boost for example, but ugh. It needs you to create an abstract “generator” (representing a source of randomness), a “distribution” (like “uniform”, or “exponential”), a function that samples according to that distribution using that random source, and finally a call to that function.

Meanwhile, here are poor-man implementations, with sucky randomness etc, but shorter by far. (ll is long long, ld is long double)

//uniform in [a,b)
int runiform_int(int a, int b) {return a + ((b-a)*ll(rand()))/(ll(RAND_MAX)+1);}
ld runiform(ld a, ld b) { return a + (b-a)*rand()/ld(RAND_MAX+1.0); }
ld rexp(ld lambda) { return -logl(runiform(0,1))/lambda; } //Mean: 1/λ
ld rnormal(ld mean, ld std) { //Using the Box-Muller transform
  return mean + std*sqrtl(-2*logl(runiform(0,1)))*sinl(2*M_PI*runiform(0,1));

Written by S

Thu, 2008-03-13 at 05:58:17

Posted in compknow

Tagged with , , ,

3 Responses

Subscribe to comments with RSS.

  1. You are assuming rand() is a uniform distribution. C++ specs give no such guarantees and indeed it is non-uniform for some of the popular implementations of the spec. Use a mersene twister or something to generate your own uniform rand or be ready for some unpleasant surprises.


    Thu, 2008-03-13 at 13:43:16

  2. I know! Hence the “sucky randomness” above. The manpage is even called “rand, srand, sranddev, rand_r — bad random number generator” :)
    (FWIW, the rand() linear congruential generator is uniform AFAIK — it’s just that its randomness is susceptible to attacks, there’s some periodic correlation, etc.) At least it has mean 1/2, and a few other tests I ran came out okay :) I don’t really care enough about the randomness in this case…


    Sat, 2008-03-15 at 04:08:20

  3. Hey,

    You could look at GMP library. Here’s the main manual page for random numbers:



    Mon, 2008-03-24 at 07:43:08

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: