Math.log() in Java not working as expected

627 views Asked by At

I am a bit confused right now. My code looks as follows:

double pc = 0.125;
double po = 0.2;  
double product = pc*Math.log(pc/po);
System.out.println(product);

I would expect the result to be -0,025514997 instead it outputs -0.4700036292457356

Where is the problem???

2

There are 2 answers

0
OldCurmudgeon On BEST ANSWER
public void test() {
    double pc = 0.125;
    double po = 0.2;
    System.out.println("pc * Math.log(pc / po) = " + pc * Math.log(pc / po));
    System.out.println("pc * Math.log10(pc / po) = " + pc * Math.log10(pc / po));
}

prints

pc * Math.log(pc / po) = -0.05875045365571695

pc * Math.log10(pc / po) = -0.0255149978319906

proving that a) there's something wrong with your question - pc * Math.log(pc / po) results in -0.05875045365571695 not -0.4700036292457356 and b) that you need to use log10 to get base 10 logs.

0
Danielson On
Math.log(a); // log e

Math.log10(a); // base 10 

Math.log(x)/Math.log(2); // log 2

Math.log(x)/Math.log(your_own); // log your_own