全部评论
我也是,估计是最后打印时没有用round, 用了%.2f from math import log
if __name__ == "__main__":
p_data = [int(i) for i in input().split()]
q_data = [int(i) for i in input().split()]
p_total = len(p_data) + 1e-5
q_total = len(q_data) + 1e-5
x_unique = set(p_data + q_data)
p_stat = {x: 0 for x in x_unique}
q_stat = {x: 0 for x in x_unique}
for x in p_data:
p_stat[x] += 1
for x in q_data:
q_stat[x] += 1
kl_val = 0
for x in x_unique:
p_proba = p_stat[x] / p_total + 1e-5
q_proba = q_stat[x] / q_total + 1e-5
kl_val += p_proba * log(p_proba / q_proba, 2)
print("%.2f" % kl_val)
为啥我一直是44.4%啊,p有q没有,或者都没有的情况也都考虑了啊,也用了setprecision(n)函数四舍五入
#include<iostream> #include<map> #include<cmath> #include<sstream> #include<vector> #include<string> using namespace std; struct single{ int p; int q; single(int i=0,int j=0) { p=i; q=j; } }; int main() { int qsum=0; int psum=0; string qq; string pp; getline(cin,pp); getline(cin,qq); istringstream ssq(qq); istringstream ssp(pp); map<int,single> T; string temp; while(ssq>>temp) { int i=stoi(temp); T[i].q++; qsum++; } while(ssp>>temp) { int i=stoi(temp); T[i].p++; psum++; } double prob=0; for(map<int,single>::iterator it=T.begin();it!=T.end();++it) { int p=(*it).second.p; int q=(*it).second.q; if(p==0)continue; double pp=(double)p/(double)psum; double qq=(double)q/(double)qsum; double t=pp*log(pp/qq); prob+=t; } printf("%.2f\n",prob); system("pause"); return 0; } 哪个大佬帮我看看哪里有错啊?一直是0
是不是数据分布的种类(1,2,3,。。。。)想少了?或者只考虑p的分布存在的值了?有时候p无,q有。我ac了这道题。
应该是精度问题吧,或者题目没有描述清楚,或者我们的理解错过了特殊情况
一样
一样一样,感觉就是按公式,结果还是,我还以为要考虑特殊情况
同
同……
相关推荐
点赞 评论 收藏
分享