From 4069cf570107133c84bbb772625db18741f25598 Mon Sep 17 00:00:00 2001 From: Christopher Haster Date: Thu, 2 Nov 2023 12:16:42 -0500 Subject: [PATCH] Tweaked test/bench prng to convert 0 -> -1 Like many prngs, xorshift breaks down when the internal state is 0. The common fix is to explicitly check for this and replace with a 1 when this happens (usually when seeding, in this API we have to check every update, this is less efficient but I don't think we really care). As a slight tweak, this now checks for 0 but replaces it with -1. This makes seed=0 different from seed=1, which is nice when using seed=range(0,n) in tests/benches. --- runners/bench_runner.c | 5 +++++ runners/test_runner.c | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/runners/bench_runner.c b/runners/bench_runner.c index 44a3637f..384995d9 100644 --- a/runners/bench_runner.c +++ b/runners/bench_runner.c @@ -587,6 +587,11 @@ uint32_t bench_prng(uint32_t *state) { // A simple xorshift32 generator, easily reproducible. Keep in mind // determinism is much more important than actual randomness here. uint32_t x = *state; + // must be non-zero, use uintmax here so that seed=0 is different + // from seed=1 and seed=range(0,n) makes a bit more sense + if (x == 0) { + x = -1; + } x ^= x << 13; x ^= x >> 17; x ^= x << 5; diff --git a/runners/test_runner.c b/runners/test_runner.c index 4e1eeb7f..ba9ca95a 100644 --- a/runners/test_runner.c +++ b/runners/test_runner.c @@ -603,6 +603,11 @@ uint32_t test_prng(uint32_t *state) { // A simple xorshift32 generator, easily reproducible. Keep in mind // determinism is much more important than actual randomness here. uint32_t x = *state; + // must be non-zero, use uintmax here so that seed=0 is different + // from seed=1 and seed=range(0,n) makes a bit more sense + if (x == 0) { + x = -1; + } x ^= x << 13; x ^= x >> 17; x ^= x << 5;