【发布时间】:2017-04-15 20:55:41
【问题描述】:
我正在尝试计算从 n 卷 s 面骰子中获得特定总和的概率。我在这个link(公式10)中找到了公式。
这是我用 C 写的代码:
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
# define n 2 // number of dices
# define s 6 // number of sides of one dice
int fact(int x){
int y = 1;
if(x){
for(int i = 1; i <= x; i++)
y *= i;
}
return y;
}
int C(int x,int y){
int z = fact(x)/(fact(y)*fact(x-y));
return z;
}
int main(){
int p,k,kmax;
double proba;
for(p = n; p <= s*n; p++){
proba = 0.0;
kmax = (p-n)/s;
for(k = 0; k <= kmax; k++)
proba += pow(-1.0,k)*C(n,k)*C(p-s*k-1,p-s*k-n);
proba /= pow((float)s,n);
printf("%5d %e\n",p,proba);
}
}
以下是结果:
两个 6 面骰子:
2 2.777778e-02
3 5.555556e-02
4 8.333333e-02
5 1.111111e-01
6 1.388889e-01
7 1.666667e-01
8 1.388889e-01
9 1.111111e-01
10 8.333333e-02
11 5.555556e-02
12 2.777778e-02
对于三个 6 面骰子:
3 4.629630e-03
4 1.388889e-02
5 2.777778e-02
6 4.629630e-02
7 6.944444e-02
8 9.722222e-02
9 1.157407e-01
10 1.250000e-01
11 1.250000e-01
12 1.157407e-01
13 9.722222e-02
14 -1.805556e-01
15 -3.703704e-01
16 -4.768519e-01
17 -5.462963e-01
18 -6.203704e-01
负概率?代码或公式有什么问题?
这是 Valgrind 报告
==9004==
==9004== HEAP SUMMARY:
==9004== in use at exit: 0 bytes in 0 blocks
==9004== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==9004==
==9004== All heap blocks were freed -- no leaks are possible
==9004==
==9004== For counts of detected and suppressed errors, rerun with: -v
==9004== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
【问题讨论】:
-
您可以使用调试器来找出答案。
-
fact(x-y) -- y 是否比 x 大?尝试发送 x-y 的绝对值以确保它始终为正。
-
同样的结果
-
你的操作顺序有问题吗...
p-s*k-1 -
3 die 的条件不一样吧?
标签: c multinomial