Skip to content

Commit 2de37bb

Browse files
author
埃博拉酱
committed
Beta distribution may generate NaN when a and b are both very small
1 parent 74470f9 commit 2de37bb

2 files changed

Lines changed: 9 additions & 1 deletion

File tree

src/Numerics.Tests/DistributionTests/Continuous/BetaTests.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,5 +405,13 @@ public void ValidateInverseCumulativeDistribution(double a, double b, double x,
405405
Assert.That(dist.InverseCumulativeDistribution(p), Is.EqualTo(x).Within(1e-6));
406406
Assert.That(Beta.InvCDF(a, b, p), Is.EqualTo(x).Within(1e-6));
407407
}
408+
409+
[TestCase(0.001)]
410+
public void ProbableNaNWhenABBothSmall(double ab)
411+
{
412+
Beta dist = new Beta(ab, ab);
413+
for (byte i = 0; i < 100; ++i)
414+
Assert.That(!double.IsNaN(dist.Sample()),"Generate NaN");
415+
}
408416
}
409417
}

src/Numerics/Distributions/Beta.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,7 @@ internal static double SampleUnchecked(System.Random rnd, double a, double b)
394394
{
395395
var x = Gamma.SampleUnchecked(rnd, a, 1.0);
396396
var y = Gamma.SampleUnchecked(rnd, b, 1.0);
397-
return x/(x + y);
397+
return x == 0 ? 0 : x / (x + y);
398398
}
399399

400400
internal static void SamplesUnchecked(System.Random rnd, double[] values, double a, double b)

0 commit comments

Comments
 (0)