簡體   English   中英

香農熵不打印任何東西

[英]Shannon entropy not printing anything

Java,Intellij IDE Coursera,計算機科學:有目的的編程 普林斯頓大學

我的程序沒有返回任何 output 因為 n 和 f[] 在 while 循環之外沒有返回任何值 - 我使用 print 語句檢查了它。 但是,當我使用相同的打印語句在 while 循環內打印 n 和 f[] 的值時,它會打印該值。 似乎 n 和 f[] 在 while 循環之外變得過時了。

問題是香農熵。 編寫一個程序 ShannonEntropy.java 接受命令行 integer m; 從標准輸入中讀取 1 到 m 之間的整數序列; 並將香農熵打印到標准 output,小數點后 4 位。 整數序列的香農熵由以下公式給出: H=−(p1log2p1+p2log2p2+…+pmlog2pm) 其中 pi 表示值為 i 的整數的比例。 如果 pi=0,則將 pilog2pi 視為 0。 如果問題不清楚,請查看

如果你能幫助我,那就太好了。 提前致謝。

public class ShannonEntropy {

public static void main(String[] args) {

int m = Integer.parseInt(args[0]);

int[] f = new int[m + 1];

int n = 0;



// calculating the frequency by incrementing the array and incrementing n alongside

while (!StdIn.isEmpty()) {

int value = StdIn.readInt();

f[value]++;

n++;

}

double entropy = 0;

for (int i = 1; i <= m; i++) {

double p = (double) f[i] / n;

System.out.println(p);

if (f[i] > 0)

entropy -= p * (Math.log(p) / Math.log(2));



}



// printing the output

StdOut.println((double) Math.round(entropy * 10000) / 10000);



}

}

您好,我已經測試了您的代碼。 您編寫 output 代碼的方式確實存在問題。

代替:

StdOut.println((double) Math.round(entropy * 10000) / 10000);

您應該使用格式化打印又名 printf() 來實現 4 個小數位,而不是使用 Math.round() 因為 1.0 將打印為 1.0 而不是所需的 1.0000

用這個:

StdOut.printf("%.4f\n" ,entropy);

有關 printf() 的更多信息,請參閱此鏈接: printf() 指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM