Files
Library/include/Void/Math/Random.hpp
T
selikhov 2e8afc471b feat(Math): versioned Xoshiro state and portable bounded draws (#10)
- Public, versioned State (algorithm identity "xoshiro256**", schema
  version 1, four words in s0..s3 order) so consumers can define their
  own wire format.
- restore() validates version and rejects the absorbing all-zero state
  without touching the current stream; from_state() builds a generator
  from saved state.
- bounded(n): unbiased rejection sampling in [0, n). Documented
  zero-bound policy: n == 0 and n == 1 return 0 without consuming
  randomness.
- 7 new tests freeze raw/bounded/state outputs for seed 42 (portable
  across targets), verify save/restore suffix equality, invalid-state
  rejection, zero/one bounds, large non-power-of-two ranges,
  independent interleaved streams and discard equivalence.
2026-12-03 09:46:15 +03:00

262 lines
7.9 KiB
C++

#pragma once
#include <algorithm>
#include <array>
#include <compare>
#include <cstdint>
#include <expected>
#include <limits>
#include <random>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Random
{
// ── Xoshiro256** PRNG (fast, good quality, no stdlib overhead) ───────────────
class Xoshiro256
{
public:
using result_type = std::uint64_t;
explicit Xoshiro256(std::uint64_t seed = 0xdeadbeefcafe1234ull) noexcept
{
// SplitMix64 seeder
auto splitmix = [](std::uint64_t& s) noexcept -> std::uint64_t {
s += 0x9e3779b97f4a7c15ull;
std::uint64_t z = s;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
return z ^ (z >> 31);
};
s_[0] = splitmix(seed);
s_[1] = splitmix(seed);
s_[2] = splitmix(seed);
s_[3] = splitmix(seed);
}
static constexpr result_type min() noexcept { return 0; }
static constexpr result_type max() noexcept
{
return std::numeric_limits<result_type>::max();
}
result_type operator()() noexcept
{
const std::uint64_t r = rotl(s_[1] * 5, 7) * 9;
const std::uint64_t t = s_[1] << 17;
s_[2] ^= s_[0];
s_[3] ^= s_[1];
s_[1] ^= s_[2];
s_[0] ^= s_[3];
s_[2] ^= t;
s_[3] = rotl(s_[3], 45);
return r;
}
void discard(unsigned long long n) noexcept
{
while (n--) operator()();
}
// ── Versioned deterministic state ────────────────────────────────────────
/// Algorithm identity for saved-stream metadata. The state schema is
/// versioned separately so a future algorithm change cannot silently
/// reinterpret old saves.
static constexpr std::string_view algorithm = "xoshiro256**";
static constexpr std::uint32_t state_version = 1;
/// Portable state: version plus the four words in xoshiro order s0..s3.
/// Consumers choose their own wire format (endianness, framing); this
/// struct defines only the identity and word order.
struct State {
std::uint32_t version{state_version};
std::array<std::uint64_t, 4> words{};
[[nodiscard]] auto operator<=>(const State&) const noexcept = default;
[[nodiscard]] bool operator==(const State&) const noexcept = default;
};
enum class StateErrorKind : std::uint8_t {
unknown_version = 0,
/// Xoshiro's all-zero state is absorbing and therefore invalid.
invalid_state,
};
struct StateError {
StateErrorKind kind{StateErrorKind::invalid_state};
[[nodiscard]] bool operator==(const StateError&) const noexcept = default;
};
[[nodiscard]] State state() const noexcept
{
return State{.version = state_version,
.words = {s_[0], s_[1], s_[2], s_[3]}};
}
/// Replace the stream with `state` only if it is valid. On failure the
/// current stream is unchanged (the caller can keep drawing).
[[nodiscard]] std::expected<void, StateError> restore(State state) noexcept
{
if (state.version != state_version) {
return std::unexpected{StateError{StateErrorKind::unknown_version}};
}
if (state.words[0] == 0 && state.words[1] == 0 &&
state.words[2] == 0 && state.words[3] == 0) {
return std::unexpected{StateError{StateErrorKind::invalid_state}};
}
s_[0] = state.words[0];
s_[1] = state.words[1];
s_[2] = state.words[2];
s_[3] = state.words[3];
return {};
}
[[nodiscard]] static std::expected<Xoshiro256, StateError>
from_state(State state) noexcept
{
Xoshiro256 rng;
if (auto restored = rng.restore(state); !restored.has_value()) {
return std::unexpected{restored.error()};
}
return rng;
}
/// Uniform integer in [0, bound) by rejection sampling (unbiased).
///
/// Zero-bound policy: `bound == 0` and `bound == 1` return 0 without
/// consuming any randomness, so callers need not special-case them and a
/// saved stream stays aligned.
[[nodiscard]] std::uint64_t bounded(std::uint64_t bound) noexcept
{
if (bound <= 1) {
return 0;
}
// 2^64 mod bound: values below it are rejected to remove modulo bias.
const std::uint64_t threshold = (0ULL - bound) % bound;
for (;;) {
const std::uint64_t value = operator()();
if (value >= threshold) {
return value % bound;
}
}
}
private:
static constexpr std::uint64_t rotl(std::uint64_t x, int k) noexcept
{
return (x << k) | (x >> (64 - k));
}
std::uint64_t s_[4];
};
// ── Thread-local default generator ───────────────────────────────────────────
inline Xoshiro256& global_rng() noexcept
{
static thread_local Xoshiro256 rng{std::random_device{}()};
return rng;
}
// ── Distributions ─────────────────────────────────────────────────────────────
/// Uniform integer in [lo, hi] (inclusive).
template <std::integral T>
[[nodiscard]] T uniform_int(T lo, T hi) noexcept
{
std::uniform_int_distribution<T> d{lo, hi};
return d(global_rng());
}
/// Uniform real in [lo, hi).
template <std::floating_point T = double>
[[nodiscard]] T uniform_real(T lo = T{0}, T hi = T{1}) noexcept
{
std::uniform_real_distribution<T> d{lo, hi};
return d(global_rng());
}
/// Bernoulli trial: true with probability p.
[[nodiscard]] inline bool coin_flip(double p = 0.5) noexcept
{
std::bernoulli_distribution d{p};
return d(global_rng());
}
/// Normal (Gaussian) sample.
[[nodiscard]] inline double normal(double mean = 0.0,
double stddev = 1.0) noexcept
{
std::normal_distribution<double> d{mean, stddev};
return d(global_rng());
}
/// Pick a random element from a non-empty span. UB if span is empty.
template <typename T>
[[nodiscard]] const T& choice(std::span<const T> items) noexcept
{
return items[uniform_int<std::size_t>(0, items.size() - 1)];
}
template <typename T>
[[nodiscard]] T& choice(std::span<T> items) noexcept
{
return items[uniform_int<std::size_t>(0, items.size() - 1)];
}
/// Shuffle a container in place using Fisher-Yates.
template <typename Container>
void shuffle(Container& c) noexcept
{
std::ranges::shuffle(c, global_rng());
}
/// Fill a span with random bytes.
inline void fill_random(std::span<std::byte> buf) noexcept
{
for (auto& b : buf) {
b = static_cast<std::byte>(uniform_int<int>(0, 255));
}
}
/// Generate a random string of length n drawn from `charset`.
[[nodiscard]] inline std::string random_string(std::size_t n,
std::string_view charset)
{
std::string s;
if (charset.empty()) return s;
s.reserve(n);
for (std::size_t i = 0; i < n; ++i) {
s += charset[uniform_int<std::size_t>(0, charset.size() - 1)];
}
return s;
}
/// Generate a random alphanumeric string of length n.
[[nodiscard]] inline std::string random_string(std::size_t n)
{
constexpr std::string_view chars =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789";
return random_string(n, chars);
}
/// Sample k distinct indices from [0, n).
[[nodiscard]] inline std::vector<std::size_t> sample_indices(std::size_t n,
std::size_t k)
{
std::vector<std::size_t> pool(n);
std::iota(pool.begin(), pool.end(), std::size_t{0});
shuffle(pool);
pool.resize(k);
return pool;
}
} // namespace Void::Random