How to calculate the logarithm of a number in any base in java?

2

I would like to know how to calculate the logarithm of a number in base 2 and on any other basis. I know that in java you can calculate the logarithm of a number in base 10 using the Math.log10 function, but I do not know how to calculate the log of any number in base 2 for example.

Thank you in advance for your attention!

    
asked by anonymous 06.07.2017 / 22:11

1 answer

3

Here's an example:

class Logaritmos {

    public static void main(String[] args) {
        System.out.println(log(2, 128));
        System.out.println(log(5, 625));
        System.out.println(log(100, 1000));
        System.out.println(log(7, 49));
    }

    public static double log(double base, double valor) {
        return Math.log(valor) / Math.log(base);
    }
}

The log method is what you want and feel free to copy and paste into your application. The main method is a test. Here is the correct and expected output:

7.0
4.0
1.4999999999999998
2.0

Just note that this 1.4999999999999998 was meant to be 1.5 , but when working with double there are always precision details.

Go here running on ideone.

    
06.07.2017 / 22:53