How can I specify the base for Math.log() in JavaScript?

后端 未结 10 1326
别那么骄傲
别那么骄傲 2020-11-28 18:02

I need a log function for JavaScript, but it needs to be base 10. I can\'t see any listing for this, so I\'m assuming it\'s not possible. Are there any math wiz

相关标签:
10条回答
  • 2020-11-28 18:29

    You can simply divide the logarithm of your value, and the logarithm of the desired base, also you could override the Math.log method to accept an optional base argument:

    Math.log = (function() {
      var log = Math.log;
      return function(n, base) {
        return log(n)/(base ? log(base) : 1);
      };
    })();
    
    Math.log(5, 10);
    
    0 讨论(0)
  • 2020-11-28 18:29
    Math.log10 = function(n) {
        return (Math.log(n)) / (Math.log(10));
    }
    

    Then you can do

    Math.log10(your_number);
    

    NOTE: Initially I thought to do Math.prototype.log10 = ... to do this, but user CMS pointed out that Math doesn't work this way, so I edited out the .prototype part.

    0 讨论(0)
  • 2020-11-28 18:30

    For base 10 use Math.log10().

    See docs at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10

    0 讨论(0)
  • 2020-11-28 18:37

    Easy, just change the base by dividing by the log(10). There is even a constant to help you

    Math.log(num) / Math.LN10;
    

    which is the same as:

    Math.log(num) / Math.log(10);
    
    0 讨论(0)
  • 2020-11-28 18:37

    If you have a number x, then use of Math.log(x) would essentially be lnx.

    To convert it to a base other than e, you can use the following function :

    function(x){ return Math.log(x)/Math.log(10); }
    
    0 讨论(0)
  • 2020-11-28 18:42

    FF 25+ supports a Math.log10 method. You may to use polyfill:

    if (!Math.log10) Math.log10 = function(t){ return Math.log(t)/Math.LN10; };
    

    MDN lists the supported browsers.

    Desktop Browsers

    Chrome    Firefox (Gecko) Internet Explorer   Opera   Safari
    38        25 (25)         Not supported       25      7.1
    

    Mobile Browsers

    Android         Chrome for Android    Firefox Mobile (Gecko)  IE Mobile      Opera Mobile    Safari Mobile
    Not supported   Not supported         25.0 (25)               Not supported  Not supported   iOS 8
    
    0 讨论(0)
提交回复
热议问题