Search code examples
javamathlogarithm

Math.log() in Java not working as expected


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???


Solution

  • 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.