Files
leonarski_fandClaude Opus 5.5 1177ce2d08 Refinement, MR: random draws the same on every standard library
std::normal_distribution and std::uniform_real_distribution are
implementation-defined, so libstdc++, libc++ and MSVC turned the same
std::mt19937 seed into different numbers: the shaken model behind the
balanced X-ray weights (and with it the whole weight ladder), the B and U
shakes, the trial kicks and the random rotations of MR and the validation
null all differed between Linux, macOS and Windows.

PortableRandom.h draws straight from the engine's 32-bit outputs: a 53-bit
uniform in [0, 1) (Python's random.random() construction), a uniform in
[a, b), and a Box-Muller normal. The six sites keep their seeds. The trial
kick also draws its three components in separate statements, since the
order of a constructor's arguments is unspecified.

RefinementPortableRandom_pinned pins the first draws to values computed
with Python's random module on a MT19937 seeded as std::mt19937 is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UqXYdHHZ4cogS1mrGUtfN7
2026-11-17 11:37:56 +01:00

36 lines
1.5 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// 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 <cmath>
#include <cstdint>
#include <random>
#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<double>((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);
}