Last active
September 17, 2015 07:46
-
-
Save iwiwi/ce0cafcb327b4bd4afe3 to your computer and use it in GitHub Desktop.
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
/* | |
* An xorshift random generator implementation, which is compatible to std::random. | |
* | |
* References: | |
* - http://cpplover.blogspot.jp/2013/03/blog-post_22.html | |
* - http://xorshift.di.unimi.it/xorshift64star.c | |
* - http://xorshift.di.unimi.it/xorshift1024star.c | |
*/ | |
#include <random> | |
#include <array> | |
#include <limits> | |
class xorshift64star { | |
public: | |
typedef uint64_t result_type; | |
static constexpr uint64_t min() { | |
return std::numeric_limits<uint64_t>::min(); | |
} | |
static constexpr uint64_t max() { | |
return std::numeric_limits<uint64_t>::max(); | |
} | |
xorshift64star(uint64_t seed) : x_(seed) {} | |
uint64_t operator()() { | |
x_ ^= x_ >> 12; | |
x_ ^= x_ << 25; | |
x_ ^= x_ >> 27; | |
return x_ * 2685821657736338717LL; | |
} | |
private: | |
uint64_t x_; | |
}; | |
class xorshift1024star { | |
public: | |
typedef uint64_t result_type; | |
static constexpr uint64_t min() { | |
return std::numeric_limits<uint64_t>::min(); | |
} | |
static constexpr uint64_t max() { | |
return std::numeric_limits<uint64_t>::max(); | |
} | |
xorshift1024star(uint64_t seed) : p_(0) { | |
xorshift64star x(seed); | |
for (int i = 0; i < 16; ++i) s_[i] = x(); | |
} | |
uint64_t operator()() { | |
uint64_t s0 = s_[p_]; | |
uint64_t s1 = s_[p_ = (p_ + 1) & 15]; | |
s1 ^= s1 << 31; // a | |
s1 ^= s1 >> 11; // b | |
s0 ^= s0 >> 30; // c | |
return (s_[ p_ ] = s0 ^ s1) * 1181783497276652981LL; | |
} | |
private: | |
int p_; | |
std::array<uint64_t, 16> s_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment