libcruft-util/test/rand/buckets.cpp

68 lines
2.2 KiB
C++
Raw Normal View History

2016-02-03 12:13:03 +11:00
#include "rand/xorshift.hpp"
#include "rand/lcg.hpp"
2016-06-30 18:15:05 +10:00
#include "rand/mwc64x.hpp"
2016-02-03 12:13:03 +11:00
#include "tap.hpp"
#include "maths.hpp"
#include "types/string.hpp"
///////////////////////////////////////////////////////////////////////////////
template <>
std::string
type_to_string<cruft::rand::xorshift<uint32_t>> (void) { return "xorshift<uint32_t>"; }
2016-02-03 12:13:03 +11:00
template <>
std::string
type_to_string<cruft::rand::xorshift<uint64_t>> (void) { return "xorshift<uint64_t>"; }
2016-02-03 12:13:03 +11:00
template <> std::string type_to_string<cruft::rand::lcg_t> (void) { return "lcg_t"; }
2016-06-30 18:15:05 +10:00
template <> std::string type_to_string<cruft::rand::mwc64x> (void) { return "mwc64x"; }
2016-02-03 12:13:03 +11:00
///////////////////////////////////////////////////////////////////////////////
/// check random outputs are roughly divisible between a number of fixed width
/// buckets.
///
/// this is not anything close to a strict statistical test. it is more aimed
/// at link testing and basic functionality verification within a small
/// resource footprint (ie, fast unit testing).
template <typename G, typename ...Args>
void
test_buckets (cruft::TAP::logger &tap, Args&& ...args)
2016-02-03 12:13:03 +11:00
{
constexpr unsigned BUCKET_BITS = 8u;
constexpr size_t BUCKET_COUNT = 1u << BUCKET_BITS;
constexpr unsigned BUCKET_MASK = BUCKET_COUNT - 1u;
constexpr unsigned EXPECTED = 1024u;
constexpr unsigned ITERATIONS = BUCKET_COUNT * EXPECTED;
unsigned buckets[BUCKET_COUNT] = {};
G gen (std::forward<Args> (args)...);
for (unsigned i = 0; i < ITERATIONS; ++i)
++buckets[gen () & BUCKET_MASK];
2016-06-30 18:15:05 +10:00
tap.expect (
std::find_if (std::cbegin (buckets),
std::cend (buckets),
[] (auto v) { return v < EXPECTED * 7 / 8; }) == std::cend (buckets),
"bucket counts for %s", type_to_string<G> ());
2016-02-03 12:13:03 +11:00
}
///////////////////////////////////////////////////////////////////////////////
int
main (int,char**)
{
cruft::TAP::logger tap;
2016-02-03 12:13:03 +11:00
test_buckets<cruft::rand::xorshift<uint32_t>> (tap, 0x1234u);
test_buckets<cruft::rand::xorshift<uint64_t>> (tap, 0x1234u);
test_buckets<cruft::rand::lcg_t> (tap, 0x1234u);
test_buckets<cruft::rand::mwc64x> (tap, 0x1234u);
2016-02-03 12:13:03 +11:00
return tap.status ();
}