Michael Pnrs
Michael Pnrs

Reputation: 125

How can I find the log 2 base of a double variable?

I'm trying to calculate the log 2 base of some double form numbers but it seems that there isn't a standard method from a libraly for that.

I tried out this code,error occurs though.

        double entropy=0;
        for(int i=0; i<26;i++){
            entropy+=-possibilityCounter[i]*log2(possibilityCounter[i]);
        }

NOTE: possibilityCounter table is full of double variables e.g 0.00133536

Any suggestion?

Upvotes: 3

Views: 1888

Answers (3)

Mark Bramnik
Mark Bramnik

Reputation: 42491

Indeed in java.util.Math you have logs for base e and 10.

However you can use the following formula:

log2(x) = log(x)/log(2)

Upvotes: 3

ardenit
ardenit

Reputation: 3890

double entropy = 0;
for(int i = 0; i < 26; i++){
    entropy += -possibilityCounter[i] * Math.log(possibilityCounter[i]) / Math.log(2);
}

Upvotes: 1

b.GHILAS
b.GHILAS

Reputation: 2303

You can calculate the log base 2 from the natural log like this

public double log2(double v) {
    return Math.log(v) / Math.log(2);
}

Upvotes: 12

Related Questions