求序列的熵

  题目:给定一个整数序列,存放在数组xs中,长度为n,请计算该序列的熵。
  熵的计算方法:对于一个长度为n的序列xs,它包含m+1中不同的取值,s0, s1, …, sm,这些取值对应的出现概率分别是p0, p1, …,pm,则这个序列的熵为H(X) = -(p0log2(p0) + p1log2(p1) + … + pm*log2(pm)). 其中,某个取值出现的概率p的计算方法为:这个取值出现的次数 除以 长度n。

入口方法:

double entropy(int[] xs) {
}

参考答案(未获得测试案例,仅供参考):

package test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class Main3 {
	public static void main(String[] args){
		int[] xs=new int[] {1,3,2,3,2,2};
		Main3 m=new Main3();
		System.out.println(m.entropy(xs));
	}
	
	double entropy(int[] xs) {
		//数组中的value作为map的key,map的value代表重复次数
		//(int)Math.ceil(log2(xs.length))只是优化,防止扩容带来的性能开销
		Map<Integer, Integer> map=new HashMap<>((int)Math.ceil(log2(xs.length)));
		
		for (int i = 0; i < xs.length; i++) {
			Integer times = map.get(xs[i]);
			if(times==null) {
				map.put(xs[i], 1);
			}else {
				map.put(xs[i], times+1);
			}
		}
		return calculate(map, xs.length);
	}
	
	public double calculate(Map<Integer, Integer> map,int total) {
		double res=0;
		double p=0;
		Collection<Integer> values = map.values();
		for (Integer times : values) {
			p=(times+0.0)/total;
			res-=p*log2(p);
		}
		return res;
	}
	
	//log2(N)=loge(N)/loge(2),loge(N)代表以e为底的N的对数,loge(2)代表以e为底的2的对数
	public double log2(double N) {
		return Math.log(N)/Math.log(2);//Math.log的底为e
	}
}

本次输出:

1.4591479170272446

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值