Skip to content

Instantly share code, notes, and snippets.

@orlp
Last active April 19, 2016 09:59
Show Gist options
  • Save orlp/c877fd75de6fe9ba7d9246187f1ec4ec to your computer and use it in GitHub Desktop.
Save orlp/c877fd75de6fe9ba7d9246187f1ec4ec to your computer and use it in GitHub Desktop.
Minimal fast random number generation, for simulation purposes. Not cryptographically secure.
#include <cstdint>
// Random 32-bit unsigned integer.
uint32_t pcg32(uint64_t& rng) {
rng = rng * 6364136223846793005ULL + 1;
int rot = rng >> 59u;
uint32_t r = (rng >> 18u) ^ rng;
return (r >> rot) | (r << (32 - rot));
}
// Random double on [0, 1), assuming IEEE754.
double uniform(uint64_t& rng) {
union { double d; uint64_t i; } u { 1.0 };
u.i |= (uint64_t(pcg32(rng)) << 20) ^ pcg32(rng);
return u.d - 1.0;
}
#include <iostream>
#include <ctime>
int main(int argc, char** argv) {
uint64_t rng = std::time(0); // Seed with time or constant value.
for (int i = 0; i < 10; ++i) std::cout << std::hex << pcg32(rng) << " ";
std::cout << "\n";
for (int i = 0; i < 10; ++i) std::cout << uniform(rng) << " ";
std::cout << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment