imneme / bounded-rands Goto Github PK
View Code? Open in Web Editor NEWMethods and Benchmarks for Random Numbers in a Range
Methods and Benchmarks for Random Numbers in a Range
First, what I've been calling the Dr Jacques method:
static int m = 1, r = 0;
int bounded_rand(int n) {
const int N = INT_MAX >> 1;
int q, d;
for (;;) {
while (m < N) {
// needs refactoring to consume 32-bit chunks
r = (r << 1) | random_bit();
m <<= 1;
}
q = m / n;
if (r < q * n)
break;
r -= n * q;
m -= n * q;
}
d = r % n;
r /= q;
m = q;
return d;
}
This is an algorithm which doesn't do much to avoid division, but it is frugal with its use of the RNG. If you include a CSRNG in the pool of generators to test against, then this may win.
The other is my own:
static uint32_t bounded_rand(rng_t& rng, uint32_t range) {
uint64_t m = uint64_t(range) << 31; // zero is fine too.
for (int i = 0; i < 3; ++i) {
uint32_t x = rng();
m = uint64_t(x) * uint64_t(range) + (m >> 32);
}
return m >> 32;
}
This is biased, but the bias is extremely small. Change 3
to whatever you need. And it's branch-free on top of being division-free, provided the loop is unrolled.
If you analyse it you'll see it's simply a long-multiplication version of the standard multiply-and-shift bounded_rand()
. Since range
is only a 32-bit value there's only one carry path to follow and the rest of the result is discarded on the fly.
Fun fact: it's also the same construction as Marsaglia's multiply-with-carry generator. I believe there's a lag-r MWC construction analogue which should use fewer calls to rng()
if anybody cared about that.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.