libcruft-util/rand/lcg.hpp

46 lines
1.1 KiB
C++

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Copyright 2015-2019 Danny Robson <danny@nerdcruft.net>
*/
#pragma once
#include "../std.hpp"
#include <type_traits>
#include <limits>
namespace cruft::rand {
/// linear congruential generator
///
/// T: output/state type
/// M: modulus
/// A: multiplier
/// C: increment
template <typename T, T M, T A, T C>
struct lcg {
public:
using result_type = T;
static_assert (std::is_unsigned_v<T>);
explicit lcg (T seed);
result_type operator() (void);
static constexpr auto min (void) { return std::numeric_limits<T>::min (); }
static constexpr auto max (void) { return std::numeric_limits<T>::max (); }
void discard (unsigned);
private:
T m_x;
};
// glibc: typedef lcg<u64, pow2(31), 1103515245, 12345> lcg_t;
using lcg_t = lcg<u64,0u,6364136223846793005ul, 1ul>;
}