Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my factorial method work with decimals? (Gamma)

Tags:

java

math

I have a method that returns the factorial of the input. It works perfectly for integers, but I cant figure out how to make it work with decimal numbers.

Here is my method currently:

public static double factorial(double d)
{
    if (d == 0.0)
    {
        return 1.0;
    }

    double abs = Math.abs(d);
    double decimal = abs - Math.floor(abs);
    double result = 1.0;

    for (double i = Math.floor(abs); i > decimal; --i)
    {
        result *= (i + decimal);
    }
    if (d < 0.0)
    {
        result = -result;
    }

    return result;
}

I found an implementation but the code wasn't shown (I lost the link) and the example given was 5.5! = 5.5 * 4.5 * 3.5 * 2.5 * 1.5*0.5! = 287.885278

So from this pattern, I just added the decimal value to i in the for-loop result *= (i + decimal)

But clearly my logic is flawed

Edit: Just realsed that the last value is 0.5!, not 0.5. This makes all the difference. So 0.5! = 0.88622 and 5.5! = 5.5 * 4.5 * 3.5 * 2.5 * 1.5 * 0.88622 which equals 287.883028125

like image 771
Kelan Avatar asked Jan 07 '23 22:01

Kelan


1 Answers

The gamma function (which generalizes factorials to real numbers) is rather tricky to implement directly. Use a library such as apache-commons-math to calculate it for you, or look at their source to get a feel of what is involved. Once available, use as follows:

public static double generalizedFactorial(double d) {
    // Gamma(n) = (n-1)! for integer n
    return Gamma.gamma(d+1);
}

Outputs:

4.0! = 24.0
5.5! = 287.88527781504433
6.0! = 720.0

Previous answer (provides a factorial-like interpretation for real numbers > 1; but since there is already an aggreed-upon extension of factorial to real numbers, please disregard this for anything practical):

public static double f(double d) {
    double r = d - Math.floor(d) + 1;
    for (;d>1; d-=1) {
        r *= d;
    }
    return r;
}

Outputs:

4.0! = 24.0
5.5! = 487.265625
6.0! = 720.0
like image 132
tucuxi Avatar answered Feb 08 '23 18:02

tucuxi