I - Information Entropy ZOJ - 3827 水

本文介绍了一种使用C++编程语言计算信息熵的方法。针对不同的单位(bit、nat、dit),通过输入概率分布并利用换底公式进行计算。文章包含完整的代码示例,展示了如何根据给定的概率值集合计算其信息熵。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:bit为2,nat为e,dit为10,求H(X)=i=1nP(xi)log b(P(xi))


题解:e取exp(1.0)即可,另外加上换底公式

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <string.h>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <list>
#include <bitset>
#include <stack>
#include <stdlib.h>
#define lowbit(x) (x&-x)
//ios::sync_with_stdio(false);
typedef long long ll;
typedef long long LL;
using namespace std;
#define e exp(1.0)
int main()
{
    int T;
    ios::sync_with_stdio(false);
    cin>>T;
    int n;
    string s;
    while(T--)
    {
        double ans = 0;
        cin>>n>>s;
        double a;
        if(s=="bit")//2
        {
            while(n--)
            {
                cin>>a;
                if(a==0) continue;
                a/=100.0;
                ans -= (a*log(a)/log(2.0));
            }
            printf("%.10f\n",ans);
            //cout<<ans<<endl;
        }
        else if(s=="nat")//e
        {
            while(n--)
            {
                cin>>a;
                if(a==0) continue;
                a/=100.0;
                ans -= (a*log(a)/log(e));
            }
            printf("%.10f\n",ans);
        }
        else//10
        {
            while(n--)
            {
                cin>>a;
                if(a==0) continue;
                a/=100.0;
                ans -= (a*log(a)/log(10.0));
            }
            printf("%.10f\n",ans);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值