libcruft-util/cruft/util/rand/lcg.cpp

66 lines
1.6 KiB
C++
Raw Normal View History

2016-02-03 12:13:03 +11:00
/*
2018-08-04 15:14:06 +10:00
* 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/.
2016-02-03 12:13:03 +11:00
*
* Copyright 2015-2019 Danny Robson <danny@nerdcruft.net>
2016-02-03 12:13:03 +11:00
*/
#include "lcg.hpp"
#include "../maths.hpp"
using cruft::rand::lcg;
2016-02-03 12:13:03 +11:00
///////////////////////////////////////////////////////////////////////////////
2016-02-03 12:13:03 +11:00
template <typename T>
static constexpr
bool is_coprime (T M, T C)
{
if (M == 0)
return true;
if (std::gcd (M, C) == 1u)
2016-02-03 12:13:03 +11:00
return true;
return false;
}
///////////////////////////////////////////////////////////////////////////////
template <typename T, T M, T A, T C>
lcg<T,M,A,C>::lcg (T seed):
m_x (seed)
{
// ensure this assertion isn't in a header, it could be pretty expensive
// to evaluate often.
static_assert (is_coprime (M, C),
"multiplier and increment must be coprime");
}
///////////////////////////////////////////////////////////////////////////////
template <typename T, T M, T A, T C>
T
lcg<T,M,A,C>::operator() (void)
{
m_x = (A * m_x + C);
if (M != 0)
m_x %= M;
return m_x;
}
///////////////////////////////////////////////////////////////////////////////
template <typename T, T M, T A, T C>
void
lcg<T,M,A,C>::discard (unsigned count)
{
while (count--)
(*this)();
}
2016-02-03 12:13:03 +11:00
///////////////////////////////////////////////////////////////////////////////
template struct cruft::rand::lcg<uint32_t, cruft::pow(31,2), 1103515245, 12345>;
template struct cruft::rand::lcg<uint64_t, 0ul, 6364136223846793005ul, 1ul>;