The Lumber Room

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

Archive for March 13th, 2008

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 , , ,