public static double IncompleteGamma(double a, double x)
{
double ans, ax, c, r;
if (x <= 0 || a <= 0) return 0.0;
if (x > 1.0 && x > a) return 1.0 - ComplementedIncompleteGamma(a, x);
/* Compute x**a * exp(-x) / gamma(a) */
ax = a * Math.Log(x) - x - LogGamma(a);
if (ax < -MAXLOG) return (0.0);
ax = Math.Exp(ax);
/* power series */
r = a;
c = 1.0;
ans = 1.0;
do
{
r += 1.0;
c *= x/r;
ans += c;
} while (c/ans > MACHEP);
return (ans*ax/a);
}