Created
July 12, 2018 20:10
-
-
Save lemire/b9596313593dcb6aa311f5e5aa60f517 to your computer and use it in GitHub Desktop.
fast alternative to the modulo reduction (code sample)
This file contains hidden or 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