Entropy

package Entropy;

import java.util.Scanner;

public class Entropy {
    public static double Entropy(String str) {
        double H = 0.0;
        int sum = 0;
        int[] letter = new int[26];
        str = str.toUpperCase();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                letter[c - 'A']++;
                sum++;
            }
        }
        for (int i = 0; i < 26; i++) {
            double p = 1.0 * letter[i] / sum;
            if (p > 0) {
                H += (p * Math.log(p) / Math.log(2));
            }

        }
        return H;
    }

    public static void main(String[] args) {
      Scanner scanner=new Scanner(System.in);
   String string= scanner.next();
double H=Entropy(string);
System.out.println(H);
    }
}

 

posted @ 2013-05-31 20:19  ilxx1988  阅读(140)  评论(0编辑  收藏  举报