簡體   English   中英

為標准輸入中的數字序列打印香農熵的問題

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

我正在嘗試為來自標准輸入的給定數字序列打印香農熵。 首先,用戶輸入一個存儲在 integer 變量“m”中的數字,然后僅將 [1,m] 之間的數字作為標准輸入的序列,然后計算該序列的香農熵。 我能夠得到 m<=4 的香農熵。 但是,對於 m>4,香農熵的結果顯示為 NaN。 有人可以幫忙嗎? 這是我的代碼-

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);

對於標准輸入和 output,我使用了StdOutStdIn庫,它們已經安裝在我的 IDE IntelliJ 中。 這是捆綁所有標准庫的下載鏈接,包括 StdOut 和 StdIn -stdlib.jar

對於 p=0 的情況,需要稍作修改,因為在這種情況下,log(p) 沒有定義。 這是修改后的代碼-

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