使用Java语言计算熵和自信息量

package demo;
import java.util.*;
public class Welcome {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        System.out.print("Enter the probability: ");
        String[] array=input.nextLine().split(" ");
        double[] probability=new double[array.length];
        if(array[0].contains("/")) {
            for(int i=0;i<array.length;i++)
                probability[i]=convertFractionToDecimal(array[i]);
        }
        else {
            for(int i=0;i<array.length;i++)
                probability[i]=Double.parseDouble(array[i]);
        }
        double entropy=0;
        for(int i=0;i<probability.length;i++)
            entropy+=probability[i]*Math.log(probability[i])/Math.log(2);
        System.out.printf("The entropy is %f bit/symbol\n",-entropy);
    }
    public static double convertFractionToDecimal(String fraction) {
        String[] array=fraction.split("/");
        return Double.parseDouble(array[0])/Double.parseDouble(array[1]);
    }
}

运行示例1:

Enter the probability: 1/10 2/10 4/10 1/10 2/10

The entropy is 2.121928 bit/symbol

运行示例2:

Enter the probability: 0.1 0.2 0.4 0.1 0.2

The entropy is 2.121928 bit/symbol

  1. 自信息量

package demo;
import java.util.Scanner;
public class Welcome {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        System.out.print("Enter the probability to calculate the amount of self information: ");
        double probability=input.nextDouble();
        double selfInformation=-Math.log(probability)/Math.log(2);
        System.out.printf("The self information is %f bit\nlog2(%f) = %f",selfInformation,probability,-selfInformation);
    }
}

运行示例:

Enter the probability to calculate the amount of self information: 0.5

The self information is 1.000000 bit

log2(0.500000) = -1.000000

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值