X-Git-Url: http://git.localhorst.tv/?a=blobdiff_plain;f=src%2Frand%2FGaloisLFSR.hpp;h=81652d85f54a64cd628c22a95d3493b6de6476cd;hb=29e8cfd4a72c248583ea9482864c016bb20f40f8;hp=395ff8f0546cc7b75cf111a4b996a7705052f29b;hpb=41652fb3d73f12e6ae4ce7380244a75a4f5c6797;p=blank.git diff --git a/src/rand/GaloisLFSR.hpp b/src/rand/GaloisLFSR.hpp index 395ff8f..81652d8 100644 --- a/src/rand/GaloisLFSR.hpp +++ b/src/rand/GaloisLFSR.hpp @@ -12,7 +12,11 @@ class GaloisLFSR { public: // seed should be non-zero explicit GaloisLFSR(std::uint64_t seed) noexcept - : state(seed) { } + : state(seed) { + if (state == 0) { + state = 1; + } + } // get the next bit bool operator ()() noexcept { @@ -38,12 +42,34 @@ public: return out = static_cast(state); } + /// special case for randrom(boolean), since static_cast(0b10) == true + bool operator ()(bool &out) noexcept { + return out = operator ()(); + } + template T Next() noexcept { T next; return (*this)(next); } + float SNorm() noexcept { + return float(Next()) * (1.0f / 2147483647.5f) - 1.0f; + } + + float UNorm() noexcept { + return float(Next()) * (1.0f / 4294967295.0f); + } + + template + typename Container::reference From(Container &c) { + return c[Next() % c.size()]; + } + template + typename Container::const_reference From(const Container &c) { + return c[Next() % c.size()]; + } + private: std::uint64_t state; // bits 64, 63, 61, and 60 set to 1 (counting from 1 lo to hi)