Skip to content

Instantly share code, notes, and snippets.

@safeng
Created October 8, 2014 01:14
Show Gist options
  • Save safeng/6d7526368bff000d8ede to your computer and use it in GitHub Desktop.
Save safeng/6d7526368bff000d8ede to your computer and use it in GitHub Desktop.
Generate uniform random numbers in [a, b] from 0/1 random number generator
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// Generate random numbers in large ranges with random number
// generator in small ranges
// For random number generator with 0/1, we can use it to generate bits
unsigned char zero_one()
{
return rand() & 1;
}
unsigned gen_rand(unsigned a, unsigned b)
{
if (a > b)
return gen_rand(b, a);
unsigned t = b - a;
unsigned res = 0;
do
{
res = 0;
for (int ii = 0; (1u << ii) <= t; ++ii) {
res <<= 1;
res |= zero_one();
}
} while (res > t); // if outside the range, retry
return res + a;
}
int main()
{
srand(time(0));
cout << "Generate " << 100 << " rand numbers" << endl;
for (int ii = 0; ii < 100; ++ii)
cout << gen_rand(0, 7) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment