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

Asked

Viewed 2,663 times

2

I would like to know how to calculate the logarithm of a number on 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 function Math.log10, but I don’t know how to calculate the log of any number in base 2 for example.

Thank you in advance for your attention!

  • When you say "base" you mean the base of the logarithm, right?

  • Would that be something like that? Math.log10(30)/Math.log(2)

  • @LINQ that’s right LINQ, I mean the basis of the logarithm.

  • @Marcondes tried to do this, but it didn’t work. He keeps giving a wrong answer to the calculations I’m doing.

1 answer

3


Here is 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 method log is what you want and feel free to copy and paste into your application. The method main test. Below 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 details regarding the accuracy.

Go here running in the ideone.

  • Thank you for answering. Solved my problem!

  • 1

    For those who stop here without greater contexts, the mathematics of the subject: log_b (a) = log(a)/log(b); log of a in base b is equal to log division of a by log of b

  • 1

    http://latex2png.com/output//latex_36c20f1e5559e1ca631a715de3d2f9c3.png

Browser other questions tagged

You are not signed in. Login or sign up in order to post.