Search code examples
javaalgorithmmathlogarithm

Algorithm behind Math.log - Java


Lately I used the Math.log() to code some program and now I ask myself how does the method log() work. How does the computer calculate the logarithm? Thanks for solution.


Solution

  • When in doubt, look at the source code (working with Java 8).

    public static double log(double a) {
        return StrictMath.log(a); // default impl. delegates to StrictMath
    }
    

    You see it calls a static method from StrictMath.java.

    static native double log(double a);
    

    What native keyword means you can read here. Basically, it says the method is implemented in another language aside from Java. I have found the folder jdk/src/share/native/java/lang/fdlibm/src/ on GitHub with the math functions. The algorithm is implemented in e_log.c. What kind of sorcery happens inside, I don't know.