// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute // SPDX-License-Identifier: GPL-3.0-only #pragma once // Random draws that are the same on every standard library. The std::mt19937 engine is fixed by the standard, // but std::uniform_real_distribution and std::normal_distribution are not, so libstdc++, libc++ and MSVC turn // one seed into different numbers. These draw straight from the engine's 32-bit outputs instead. #include #include #include #include "../../common/JFJochMath.h" // A uniform double in [0, 1): 27 + 26 bits of two outputs make a 53-bit integer, times 2^-53 (as Python's // random.random() does, so the values can be checked there). inline double PortableUniform(std::mt19937 &rng) { const uint64_t a = rng() >> 5; const uint64_t b = rng() >> 6; return static_cast((a << 26) | b) * (1.0 / 9007199254740992.0); } // A uniform double in [lo, hi). inline double PortableUniform(std::mt19937 &rng, double lo, double hi) { return lo + (hi - lo) * PortableUniform(rng); } // A normal draw, one per two uniforms (1 - u is in (0, 1], so the logarithm is finite). // Following Box & Muller (1958) Ann. Math. Statist. 29, 610-611 inline double PortableNormal(std::mt19937 &rng, double mean, double sigma) { const double u1 = PortableUniform(rng); const double u2 = PortableUniform(rng); return mean + sigma * std::sqrt(-2.0 * std::log(1.0 - u1)) * std::cos(2.0 * PI * u2); }