How can I get my factor method to work with decimals? (Gamma)

I have a method that returns input factorial. It works great for integers, but I can't figure out how to make it work with decimal numbers.

Here is my method:

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 was not 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 template, I just added the decimal value to iin the for-loopresult *= (i + decimal)

But it is clear that my logic is wrong.

Edit: it's just that the last value is 0.5 !, not 0.5. All of this matters. So, 0.5! = 0.88622and 5.5!= 5.5 * 4.5 * 3.5 * 2.5 * 1.5 * 0.88622, which is equal to287.883028125

+4
source share
2 answers

gamma ( ) . , apache-commons-math, , , , . :

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

:

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

( > 1, , , ):

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

:

4.0! = 24.0
5.5! = 487.265625
6.0! = 720.0
+5

x โˆˆ R, x โˆˆ N. : . ( 5.0, 5.1)

: "" , ( ) , . " ".

+4

Source: https://habr.com/ru/post/1598884/


All Articles