# The Lumber Room

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

## Poor man’s random number generators in C++

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 +05:30

Posted in compknow

Tagged with , , ,

### 3 Responses

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.

anshul

Thu, 2008-03-13 at 13:43:16 +05:30

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…

S

Sat, 2008-03-15 at 04:08:20 +05:30

3. Hey,

You could look at GMP library. Here’s the main manual page for random numbers: http://gmplib.org/manual/Random-Number-Functions.html

Rgds,
SimpleIT.

SimpleIT

Mon, 2008-03-24 at 07:43:08 +05:30