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
|
|
|
*
|
2019-02-21 20:53:07 +11:00
|
|
|
* Copyright 2015-2019 Danny Robson <danny@nerdcruft.net>
|
2016-02-03 12:13:03 +11:00
|
|
|
*/
|
|
|
|
|
|
|
|
#include "lcg.hpp"
|
|
|
|
|
2016-10-11 23:47:57 +11:00
|
|
|
#include "../maths.hpp"
|
|
|
|
|
2018-08-05 14:42:02 +10:00
|
|
|
using cruft::rand::lcg;
|
2016-02-03 12:13:03 +11:00
|
|
|
|
|
|
|
|
2016-06-29 17:55:12 +10: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;
|
2018-03-11 15:21:36 +11:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2016-07-01 16:21:13 +10:00
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
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
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
2018-08-05 14:42:02 +10:00
|
|
|
template struct cruft::rand::lcg<uint32_t, cruft::pow(31,2), 1103515245, 12345>;
|
|
|
|
template struct cruft::rand::lcg<uint64_t, 0ul, 6364136223846793005ul, 1ul>;
|