Skip to content

Commit c578a38

Browse files
author
埃博拉酱
committed
Handle a==b==0 case when it always generates NaN
1 parent 1e0ca92 commit c578a38

1 file changed

Lines changed: 11 additions & 2 deletions

File tree

src/Numerics/Distributions/Beta.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -393,11 +393,20 @@ public IEnumerable<double> Samples()
393393
internal static double SampleUnchecked(System.Random rnd, double a, double b)
394394
{
395395
double x, y;
396-
do
396+
if (a == b)
397397
{
398398
x = Gamma.SampleUnchecked(rnd, a, 1.0);
399399
y = Gamma.SampleUnchecked(rnd, b, 1.0);
400-
} while (x == 0 && y == 0);
400+
//When a==b (and possibly a==b==0), return value is equally possible to be 0 or 1
401+
if (x == 0 && y == 0)
402+
return Bernoulli.Sample(0.5);//In particular, when a==b==0, Beta distribution degradates to Bernoulli distribution.
403+
}
404+
else
405+
do
406+
{
407+
x = Gamma.SampleUnchecked(rnd, a, 1.0);
408+
y = Gamma.SampleUnchecked(rnd, b, 1.0);
409+
} while (x == 0 && y == 0);//When a!=b, return value is not equally possible to be 0 or 1. Regenerate.
401410
return x / (x + y);
402411
}
403412

0 commit comments

Comments
 (0)