3
$\begingroup$

I need a C# implementation of the gamma function that produces correct exact answers at positive integer inputs. I took a look at MathNet.Numerics Meta.Numerics. In both cases, if you calculate something like gamma(5)-4!, evaluating the latter by integer arithmetic, you get an answer whose absolute value is approximately 10^-14, instead of the expected zero.

I could code in the integers as a special case. But that would lead to some strange behavior; for example, my gamma function might not be monotonically increasing for x>=2.

Is anyone aware of a library that will work?

$\endgroup$
3
$\begingroup$

The GSL implementation of the Gamma function stores the integer factorial cases up to 297 for double precision (integers greater than that overflow), and uses a table of those values directly for integer arguments (see lines 42-555 or so). Any error you see in those values should be due to loss of precision from converting an integer to a double, or because the value is so large, you can't store the exact integer in a double and lose the least significant figures. The estimated absolute error is an machine epsilon times the function value, or roughly an ulp, which is about as good as you can get. For $\Gamma(5) = 4!$, this would also be around $10^{-14}$, at worst (I get $24 \times 2.22 \times 10^{-16} = 5.328 \times 10^{-15}$, which rounds up to $10^{-14}$); it is a cost of using double precision. If you need exact answers for integer arguments, and you will only have integer arguments between 0 and 18 inclusive, consider using a factorial function that returns long integers.

| cite | improve this answer | |
$\endgroup$
0
$\begingroup$

The following code will give you the expected zero

static void Main(string[] args)
{
    int a = 24;
    double result = alglib.gammafunction(5) - a;
    Console.WriteLine(result);
}

The library used is here alglib

| cite | improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.