![](/img/trans.png)
[英]Problem with printing shannon entropy for a sequence of numbers from standard input
[英]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.