From 1e0ca927f17162525f335797a631bf85f9b71f39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9F=83=E5=8D=9A=E6=8B=89=E9=85=B1?= Date: Sat, 8 Jan 2022 15:20:59 +0800 Subject: [PATCH] Make Beta result equally possible to be 0 or 1 but not NaN when a and b are both very small --- src/Numerics/Distributions/Beta.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Numerics/Distributions/Beta.cs b/src/Numerics/Distributions/Beta.cs index 8eec4c14..c6e9f7c1 100644 --- a/src/Numerics/Distributions/Beta.cs +++ b/src/Numerics/Distributions/Beta.cs @@ -392,9 +392,13 @@ namespace MathNet.Numerics.Distributions /// a random number from the Beta distribution. internal static double SampleUnchecked(System.Random rnd, double a, double b) { - var x = Gamma.SampleUnchecked(rnd, a, 1.0); - var y = Gamma.SampleUnchecked(rnd, b, 1.0); - return x == 0 ? 0 : x / (x + y); + double x, y; + do + { + x = Gamma.SampleUnchecked(rnd, a, 1.0); + y = Gamma.SampleUnchecked(rnd, b, 1.0); + } while (x == 0 && y == 0); + return x / (x + y); } internal static void SamplesUnchecked(System.Random rnd, double[] values, double a, double b)