Search code examples
c#mathnet-numerics

c# MathNet Gamma distribution sampling not matching


I am trying to implement an event time sampling for different distributions using the MathNet library. I have them working for exponential, normal and weibull but the same process is not working for Gamma anyone know what I am doing wrong?

Testing Example to get mean.

    using System;
    using MathNet.Numerics.Distributions;

    public class Program
    {
        public static void Main()
        {
            double sum = 0.0;
            var dist = new Gamma(0.5,50);
            int runs = 1000000;
            for (int i=0; i<runs; i++)
            {
                sum += dist.Sample();
            }
            Console.WriteLine((sum/runs).ToString());
        }
    }

Returns: ~0.01

Using online calculator https://keisan.casio.com/exec/system/1180573218 I get 11.37 for the mean. (CD 0.5, shape 0.5 scale 50)


Solution

  • There are two things to keep in mind:

    1. Math.Net is using shape and rate (or inverse scale) definition of gamma distribution, while most online calculators are using shape and scale.
    2. The lower (or upper) CDF is not equal the expectation value of the distribution: if you do the integral to calculate the expected value, you get E[X] = shape/rate, that is quite close to the result you get from your code