资源描述:
《C语言求信息熵,条件熵,联合熵》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、#include#include#defineu20inti,j,n,m;floatH_X,H_Y,H_XY,H_XpY,Pypx[u][u],Px[u],H_YpX,Py[u],Pxpy[u][u],Pxy[u][u];/*H_X=H(X)平均自信息;H_XY=H(XY)联合熵;H_XpY=H(X
2、Y)、H_YpX=H(Y
3、X)条件熵;Pypx[i][j]=P(y[j]
4、x[i])条件概率;Px[i]=P(x[i])发x[i]的概率;H_XpY=H(Y/X)条件熵;Py[j]=P(y[j])收到y[j]的概率;Px
5、py[i][j]=P(x[i]/y[j])条件概率;Pxy[i][j]=P(x[i]y[j])联合概率*//*定义以2为底的对数函数*/floatlog2(floatx){floatz;z=(float)(log(x)/log(2));returnz;}/*求信源熵函数*/floatentropy(float*x,intn){floatz=0;for(i=1;i<=n;i++){z+=(*(x+i))*log2(1/(*(x+i)));}returnz;}/*求联合熵的函数*/floatjoint_entropy(float(*p)[u]){floa
6、tz=0;for(i=1;i<=n;i++)for(j=1;j<=m;j++){z+=*(p[i]+j)*log2(1/(*(p[i]+j)));}returnz;}main(){floats=0;printf("pleaseinputthedimensionof'X'and'Y'");scanf("%d%d",&n,&m);printf("ThedimensionofXisn=%dThedimensionofYism=%dPleaseinputtheconditionprobability:P(y[j]/x[i]),",n,m)
7、;printf("(afteryouinputonenumberpleaseclickthe'enter')");/*条件概率P(y[j]/x[i])赋值*/for(i=1;i<=n;i++){for(j=1;j<=m;j++){printf("P(y[%d]/x[%d])=",j,i);scanf("%f",&Pypx[i][j]);}}printf("pleaseinputP(x[i]):(afteryouinputonenumberpleaseclickthe'enter')");for(i=1;i<=n;i++){printf("P(
8、x[%d])=",i);scanf("%f",&Px[i]);}/*判断输入X的概率是否正确,不正确则退出程序*/for(i=1;i<=n;i++){if((Px[i]<0)
9、
10、(Px[i]>1)){printf("Pleaseinputrightvalueofprobability");gotoEnd_exe;}s+=Px[i];}if((s-1)*(s-1)>0.001){printf("Pleaseinputtherightvalueofprobability");gotoEnd_exe;}for(i=1;i<=n;i++){s=0;f
11、or(j=1;j<=m;j++){s+=Pypx[i][j];}if((s-1)*(s-1)>0.001){printf("Pleaseinputtherightvalueofprobability");gotoEnd_exe;}}/*计算Py[j]=P(y[j])收到y[j]的概率;Pxpy[i][j]=P(x[i]/y[j])条件概率;Pxy[i][j]=P(x[i]y[j])联合概率*/for(i=1;i<=n;i++){for(j=1;j<=m;j++){Pxy[i][j]=Pypx[i][j]*Px[i];printf("Px[%d]y
12、[%d]=%f",i,j,Pxy[i][j]);}}for(j=1;j<=m;j++){s=0;for(i=1;i<=n;i++)s+=Pxy[i][j];Py[j]=s;printf("P(y[%d])=%f",j,Py[j]);}for(i=1;i<=n;i++){for(j=1;j<=m;j++){Pxpy[i][j]=Pxy[i][j]/Py[j];printf("P(x[%d]/y[%d])=%f",i,j,Pxpy[i][j]);}}/*结束计算Py[j]=P(y[j])收到y[j]的概率;Pxpy[i][j]=P(x[i]/
13、y[j])条件概率;Pxy[i][j]=P(x[i]y[j])联合概率*//*输出信源熵*/H_X=entr