Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JuanDiegoMontoya/d8c8afdfc80c9dd33bc63f4a169f9eb5 to your computer and use it in GitHub Desktop.
Save JuanDiegoMontoya/d8c8afdfc80c9dd33bc63f4a169f9eb5 to your computer and use it in GitHub Desktop.
inline uint64_t xorshf96()
{
static thread_local uint64_t x = 123456789, y = 362436069, z = 521288629;
x ^= x << 16;
x ^= x >> 5;
x ^= x << 1;
const uint64_t t = x;
x = y;
y = z;
z = t ^ x ^ y;
return z;
}
inline uint64_t xorshf96(uint64_t& x, uint64_t& y, uint64_t& z)
{
x ^= x << 16;
x ^= x >> 5;
x ^= x << 1;
const uint64_t t = x;
x = y;
y = z;
z = t ^ x ^ y;
return z;
}
inline double rng()
{
uint64_t bits = 1023ull << 52ull | xorshf96() & 0xfffffffffffffull;
double dst;
memcpy(&dst, &bits, sizeof(double));
return dst - 1.0;
}
template<typename T, typename Q>
T map(T val, Q r1s, Q r1e, Q r2s, Q r2e)
{
return (val - r1s) / (r1e - r1s) * (r2e - r2s) + r2s;
}
inline double rng(double low, double high)
{
return map(rng(), 0.0, 1.0, low, high);
}
// generator
class RNG
{
public:
RNG()
{
void* val = this;
memcpy(&x, &val, sizeof(uint64_t));
}
RNG(uint64_t s) : x(s) {}
double Get()
{
uint64_t bits = 1023ull << 52ull | xorshf96(x, y, z) & 0xfffffffffffffull;
double dst;
memcpy(&dst, &bits, sizeof(double));
return dst - 1.0;
}
double Get(double low, double high)
{
return map(Get(), 0.0, 1.0, low, high);
}
private:
uint64_t x{};
uint64_t y{ 362436069 };
uint64_t z{ 521288629 };
};
inline thread_local RNG random;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment