mathnet/mathnet-numerics

Beta distribution Sample method can return NaN

lucvalentino opened this issue · 1 comments

Tested with Math.Net v. 4.15
The Beta.Sample() method returns NaN for some a and b parameters. It can be reproduced by using:
a = 4.2430007555736642E-06
b = 0.0012675539420686256

The problem is in this method:

internal static double SampleUnchecked(System.Random rnd, double a, double b)

{
  double num = Gamma.SampleUnchecked(rnd, a, 1.0);
  return num / (num + Gamma.SampleUnchecked(rnd, b, 1.0));
}

if num = 0 and Gamma.SampleUnchecked(rnd, b, 1.0) is also 0 we get an NaN.
This could fix the issue:

internal static double SampleUnchecked(System.Random rnd, double a, double b)
{
  double num = Gamma.SampleUnchecked(rnd, a, 1.0);
  if(num == 0.0)
    { 
       return 0d
    }
  return num / (num + Gamma.SampleUnchecked(rnd, b, 1.0));
}

This issue seems to be fixed in version 5.0