关于小数点的阶乘计算(java版)
前段时间项目需要求小数点的阶乘,当时就懵了,在网络找了好久,伽马函数公式、高数、等各种找,找了很久也不是很满意,最后无意在stackoverflow的一段代码得到启发。
至于关于数学知识,请移步于此:LDA-math-神奇的Gamma函数(1) – 我爱自然语言处理。
下面直接贴代码:
/**
* gamma函数 求小数点的阶乘 -----java
* by tiger 2013年10月23日
*/
public class Gamma2 {
static double[] Array = {0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};
static int num = 7;
//测试的数组
static double[] m = {0.5, 1.3, 2.6, 3.3, 4.8, 5.3, 5.8, 6.9, 7.5, 8.2, 20.1, 85.5};
public static void main(String[] arg) {
for (int i = 0; i < m.length; i++) {
System.out.println("result:" + gamma(m[i] + 1));
}
}
public static double gamma(double z) {
if (z < 0.5) {
return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z));
} else {
z -= 1;
double x = Array[0];
for (int i = 1; i < (num + 2); i++) {
x += Array[i] / (z + i);
}
double t = z + num + 0.5;
return Math.sqrt(2 * Math.PI) * Math.pow(t, (z + 0.5)) * Math.exp(-t) * x;
}
}
}