Search code examples
javascriptmathlogarithm

Math.log returns incorrect value


I found a bug in calculating logarithm using Math.log function in JavaScript. For example, consider a number (say 0.1), actual log value of 0.1 to the base 10 is -1.

But when I use Math.log function in javascript it returns -2.302585. Clearly, this is wrong, So, should I write my own function to calculate logarithm or is there any other methods available in JavaScript to calculate logarithm manually ?


Solution

  • From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log:

    The Math.log() function returns the natural logarithm (base e) of a number.

    Perhaps you want Math.log10, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10, but not supported in IE.

    Basic math says you can convert a natural logarithm to a base 10 logarithm by dividing by 2.303. This constant is defined as Math.LN10, so:

    function log(x) {
        return Math.log(x) / Math.LN10;
    }
    

    or more generally:

    function log(x, base) {
        return Math.log(x) / Math.log(base);
    }