mercredi 8 juillet 2020

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. I'm able to get shannon entropy for m<=4. However, for m>4, the result for shannon entropy is displayed as 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 theStdOut and StdIn libraries, which were already installed in my IDE IntelliJ. Here's the download link which bundles all the standard libraries including StdOut and StdIn- stdlib.jar.

Aucun commentaire:

Enregistrer un commentaire