-
-
Save zchee/8fe8e704667ac518a2645a3e1b7b34fb to your computer and use it in GitHub Desktop.
fast alternative to the modulo reduction (code sample)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdint> | |
using namespace std; | |
// we are going to generate random numbers using | |
// an xorshift generator | |
static uint32_t xorshift_y; | |
void xorshift32_seed(uint32_t seed) { xorshift_y = seed;} | |
uint32_t xorshift32(void) { | |
xorshift_y ^= (xorshift_y << 13); | |
xorshift_y ^= (xorshift_y >> 17); | |
return xorshift_y ^= (xorshift_y << 5); | |
} | |
uint32_t reduce(uint32_t x, uint32_t N) { | |
return (((uint64_t)x * (uint64_t)N) >> 32); | |
} | |
int main() { | |
// seeding the rng | |
xorshift32_seed(1234); | |
// we print 10 numbers | |
for(int k = 0; k < 10; k++) | |
cout<< reduce(xorshift32(), 7) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment