mathnet / mathnet-numerics

Math.NET Numerics
http://numerics.mathdotnet.com
MIT License
3.44k stars 891 forks source link

Beta distribution Sample method can return NaN #1040

Closed lucvalentino closed 7 months ago

lucvalentino commented 8 months ago

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));
}
lucvalentino commented 7 months ago

This issue seems to be fixed in version 5.0