From c58408b3aabfd4fd0e32d6d2b8fd69026ed40937 Mon Sep 17 00:00:00 2001 From: maxisoft Date: Sun, 19 Nov 2023 12:46:54 +0100 Subject: [PATCH] Modify GaussianRandom class to match Wikipedia C++ implementation of Box-Muller formula This commit modifies the GaussianRandom class to use the same logic as the C++ implementation of the Box-Muller formula that is shown on Wikipedia. This involves using a do-while loop to generate a non-zero uniform random number u1, and checking if it is greater than the smallest positive double value (double.Epsilon). This ensures that the logarithm and square root operations do not produce NaN or infinity values. This improves the robustness and accuracy of the GaussianRandom class. --- ASFFreeGames/RandomUtils.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ASFFreeGames/RandomUtils.cs b/ASFFreeGames/RandomUtils.cs index 378d6aa..b4f8dec 100644 --- a/ASFFreeGames/RandomUtils.cs +++ b/ASFFreeGames/RandomUtils.cs @@ -43,9 +43,14 @@ private double NextDouble() { } Span bytes = stackalloc byte[16]; - Fill(bytes); Span ulongs = MemoryMarshal.Cast(bytes); - double u1 = ulongs[0] / (double) ulong.MaxValue; + double u1; + + do { + GetNonZeroBytes(bytes); + u1 = ulongs[0] / (double) ulong.MaxValue; + } while (u1 <= double.Epsilon); + double u2 = ulongs[1] / (double) ulong.MaxValue; // Box-Muller formula