[英]How can I make my factorial method work with decimals? (Gamma)
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
我找到了一个实现,但代码没有显示(我丢失了链接),给出的例子是5.5! = 5.5 * 4.5 * 3.5 * 2.5 * 1.5*0.5! = 287.885278
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)
所以从这个模式,我只是在for循环result *= (i + decimal)
中将十进制值添加到i
result *= (i + decimal)
But clearly my logic is flawed 但显然我的逻辑存在缺陷
Edit: Just realsed that the last value is 0.5!, not 0.5. 编辑:刚刚意识到最后一个值是0.5!而不是0.5。 This makes all the difference. 这一切都有所不同。 So 0.5! = 0.88622
所以0.5! = 0.88622
0.5! = 0.88622
and 5.5!
0.5! = 0.88622
和5.5!
= 5.5 * 4.5 * 3.5 * 2.5 * 1.5 * 0.88622
which equals 287.883028125
= 5.5 * 4.5 * 3.5 * 2.5 * 1.5 * 0.88622
等于287.883028125
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. 使用诸如apache-commons-math之类的库来为您计算它,或者查看它们的源代码以了解所涉及的内容。 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 ): 以前的答案 ( 为实数提供了一个类似于因子的解释> 1;但由于已经存在对于实数的阶乘扩展,所以请忽略这一点以获得实际数字 ):
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
Factorial isn't actually defined for x€R, only for x€N. Factorial实际上并未定义为x€R,仅适用于x€N。 In words: you can't calculate the factorial of a decimal. 用词:你不能计算小数的阶乘。 (You can for 5.0, but not 5.1) (你可以5.0,但不是5.1)
Edit: Thats the view for "traditional" factorial, for (really rarely needed) decimal factorial, see "gamma function". 编辑:这是“传统”阶乘的视图,对于(真的很少需要)十进制阶乘,请参阅“伽玛函数”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.