| 1 |
//===----------------------------------------------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
/// |
| 9 |
/// \file |
| 10 |
/// This file contains the definition of the RandomState class, a fast and |
| 11 |
/// lightweight pseudo-random number generator. |
| 12 |
/// |
| 13 |
/// The implementation is based on the xorshift* generator, seeded using the |
| 14 |
/// SplitMix64 generator for robust initialization. For more details on the |
| 15 |
/// algorithm, see: https://en.wikipedia.org/wiki/Xorshift |
| 16 |
/// |
| 17 |
//===----------------------------------------------------------------------===// |
| 18 |
|
| 19 |
#ifndef MATHTEST_RANDOMSTATE_HPP |
| 20 |
#define MATHTEST_RANDOMSTATE_HPP |
| 21 |
|
| 22 |
#include <cstdint> |
| 23 |
|
| 24 |
struct SeedTy { |
| 25 |
uint64_t Value; |
| 26 |
}; |
| 27 |
|
| 28 |
class [[nodiscard]] RandomState { |
| 29 |
uint64_t State; |
| 30 |
|
| 31 |
[[nodiscard]] static constexpr uint64_t splitMix64(uint64_t X) noexcept { |
| 32 |
X += 0x9E3779B97F4A7C15ULL; |
| 33 |
X = (X ^ (X >> 30)) * 0xBF58476D1CE4E5B9ULL; |
| 34 |
X = (X ^ (X >> 27)) * 0x94D049BB133111EBULL; |
| 35 |
X = (X ^ (X >> 31)); |
| 36 |
return X ? X : 0x9E3779B97F4A7C15ULL; |
| 37 |
} |
| 38 |
|
| 39 |
public: |
| 40 |
explicit constexpr RandomState(SeedTy Seed) noexcept |
| 41 |
: State(splitMix64(Seed.Value)) {} |
| 42 |
|
| 43 |
inline uint64_t next() noexcept { |
| 44 |
uint64_t X = State; |
| 45 |
X ^= X >> 12; |
| 46 |
X ^= X << 25; |
| 47 |
X ^= X >> 27; |
| 48 |
State = X; |
| 49 |
return X * 0x2545F4914F6CDD1DULL; |
| 50 |
} |
| 51 |
}; |
| 52 |
|
| 53 |
#endif // MATHTEST_RANDOMSTATE_HPP |