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
Kelan source
share