简体   繁体   English

香农熵不打印任何东西

[英]Shannon entropy not printing anything

Java, Intellij IDE Coursera, Computer Science: Programming with a Purpose Princeton University Java,Intellij IDE Coursera,计算机科学:有目的的编程 普林斯顿大学

My program is not returning any output because n and f[] aren't returning any value outside the while loop - I checked it using the print statement.我的程序没有返回任何 output 因为 n 和 f[] 在 while 循环之外没有返回任何值 - 我使用 print 语句检查了它。 However, when I use the same print statement to print the value of n and f[] inside the while loop it prints the value.但是,当我使用相同的打印语句在 while 循环内打印 n 和 f[] 的值时,它会打印该值。 It seems like n and f[] becomes obsolete outside the while loop.似乎 n 和 f[] 在 while 循环之外变得过时了。

The question is Shannon entropy.问题是香农熵。 Write a program ShannonEntropy.java that takes a command-line integer m;编写一个程序 ShannonEntropy.java 接受命令行 integer m; reads a sequence of integers between 1 and m from standard input;从标准输入中读取 1 到 m 之间的整数序列; and prints the Shannon entropy to standard output, with 4 digits after the decimal point.并将香农熵打印到标准 output,小数点后 4 位。 The Shannon entropy of a sequence of integers is given by the formula: H=−(p1log2p1+p2log2p2+…+pmlog2pm) where pi denotes the proportion of integers whose value is i.整数序列的香农熵由以下公式给出: H=−(p1log2p1+p2log2p2+…+pmlog2pm) 其中 pi 表示值为 i 的整数的比例。 If pi=0, then treat pilog2pi as 0. If the question is unclear please take a look如果 pi=0,则将 pilog2pi 视为 0。 如果问题不清楚,请查看

It will be great if you can help me out.如果你能帮助我,那就太好了。 Thanks in advance.提前致谢。

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



}

}

Hi I have tested your code.您好,我已经测试了您的代码。 There is indeed a problem with the way you wrote your output code.您编写 output 代码的方式确实存在问题。

Instead of:代替:

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

You should use formatted printing aka printf() to achieve 4 decimal places instead of using Math.round() as 1.0 will be printed as 1.0 instead of the desired 1.0000您应该使用格式化打印又名 printf() 来实现 4 个小数位,而不是使用 Math.round() 因为 1.0 将打印为 1.0 而不是所需的 1.0000

Use this:用这个:

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

For more regarding printf(), refer to this link: printf() guide有关 printf() 的更多信息,请参阅此链接: printf() 指南

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

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