X-Git-Url: http://git.localhorst.tv/?a=blobdiff_plain;f=src%2Frand%2FGaloisLFSR.hpp;h=f8a61e23f3f7c721689d7e0ff4a2404aa671f412;hb=fab49d91255ef7d265817213c3da7e5f81df97a0;hp=88a1d37e899f1b26e369a727a804d7755ba7d33e;hpb=b7d09e1e35ef90282c97509e0020b20db3c7ea9f;p=blank.git diff --git a/src/rand/GaloisLFSR.hpp b/src/rand/GaloisLFSR.hpp index 88a1d37..f8a61e2 100644 --- a/src/rand/GaloisLFSR.hpp +++ b/src/rand/GaloisLFSR.hpp @@ -1,6 +1,7 @@ #ifndef BLANK_RAND_GALOISLFSR_HPP_ #define BLANK_RAND_GALOISLFSR_HPP_ +#include #include #include @@ -11,10 +12,25 @@ class GaloisLFSR { public: // seed should be non-zero - explicit GaloisLFSR(std::uint64_t seed) noexcept; + explicit GaloisLFSR(std::uint64_t seed) noexcept + : state(seed) { + if (state == 0) { + state = 1; + } + } // get the next bit - bool operator ()() noexcept; + bool operator ()() noexcept { + bool result = state & 1; + state >>= 1; + if (result) { + state |= 0x8000000000000000; + state ^= mask; + } else { + state &= 0x7FFFFFFFFFFFFFFF; + } + return result; + } template T operator ()(T &out) noexcept { @@ -27,12 +43,43 @@ 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) { + assert(c.size() > 0); + return c[Next() % c.size()]; + } + template + typename Container::const_reference From(const Container &c) { + assert(c.size() > 0); + 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) static constexpr std::uint64_t mask = 0xD800000000000000; }; + } #endif