二项分布。估计用以下代码计算binomial(100,50,0.25)将会产生的递归调用次数:
public static double binomial(int N,int k,double p)
{
if (N0 && k0) return 1.0;
if (N<0 || k<0) return 0.0;
return (1.0-p)binomial(N-1,k,p)+pbinomial(N-1,k-1,p);
}
将已经计算过的值保存在数组中并给出一个更好的实现。
代码-太难了没看懂
public static void main(String[] args) {
int N = 100;
double p = 0.25;
int k = 50;
binomial(N,50,p);
double[][] f = new double[N+1][k+1];
f[0][0] = 1.0;
for (int i = 1; i < N+1; i ++){
f[i][0] = f[i-1][0]*(1-p);
}
for (int i = 1; i < N+1; i ++){
for (int j = 1; j < i+1 && j < k+1; j ++){
f[i][j] = f[i][j]*(1-p)+f[i-1][j-1]*p;
}
}
System.out.println(f[N][k]);
}
}