简体   繁体   English

为标准输入中的数字序列打印香农熵的问题

[英]Problem with printing shannon entropy for a sequence of numbers from standard input

I'm trying to print shannon entropy for a given sequence of numbers from standard input.我正在尝试为来自标准输入的给定数字序列打印香农熵。 Firstly, the user enters a number stored in integer variable "m" and then only numbers between [1,m] will be taken as the sequence from the standard input and then, the shannon entropy is calculated for that sequence.首先,用户输入一个存储在 integer 变量“m”中的数字,然后仅将 [1,m] 之间的数字作为标准输入的序列,然后计算该序列的香农熵。 I'm able to get shannon entropy for m<=4.我能够得到 m<=4 的香农熵。 However, for m>4, the result for shannon entropy is displayed as NaN.但是,对于 m>4,香农熵的结果显示为 NaN。 can someone help?有人可以帮忙吗? Here's my code-这是我的代码-

int m = Integer.parseInt(args[0]);
    int[] xi = new int[m + 1];
    int total = 0;
    while (!StdIn.isEmpty()) {
        int x = StdIn.readInt();
        if (x > 0 && x <= m) {
            xi[x] += 1;
            total++;
        }
    }
    double entropy = 0;
    for (int i = 1; i <= m; i++) {
        double p = (double) xi[i] / total;
        double plog = p * (Math.log(p) / Math.log(2));
        entropy -= plog;
    }
    StdOut.printf("%.4f", entropy);

For standard input and output, I've used the StdOut andStdIn libraries, which were already installed in my IDE IntelliJ.对于标准输入和 output,我使用了StdOutStdIn库,它们已经安装在我的 IDE IntelliJ 中。 Here's the download link which bundles all the standard libraries including StdOut and StdIn- stdlib.jar .这是捆绑所有标准库的下载链接,包括 StdOut 和 StdIn -stdlib.jar

There is a slight modification that needs to be done for the case when p=0, because in that case, log(p) is not defined.对于 p=0 的情况,需要稍作修改,因为在这种情况下,log(p) 没有定义。 Here is the modified code-这是修改后的代码-

double entropy = 0;
    for (int i = 1; i <= m; i++) {
        if (xi[i] > 0) {
            double p = (double) xi[i] / (double) total;
            double plog = p * (Math.log(p) / Math.log(2));
            entropy -= plog;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM