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

后端 未结 10 1334
别那么骄傲
别那么骄傲 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:42

    Math.log10(x)!

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

    the answer here would cause obvious precision problem and is not reliable in some use cases

    > Math.log(10)/Math.LN10
    1
    
    > Math.log(100)/Math.LN10
    2
    
    > Math.log(1000)/Math.LN10
    2.9999999999999996
    
    > Math.log(10000)/Math.LN10
    4
    
    0 讨论(0)
  • 2020-11-28 18:55
    const logBase = (n, base) => Math.log(n) / Math.log(base);
    

    https://en.wikipedia.org/wiki/Logarithm#Change_of_base

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

    "Change of Base" Formula / Identity

    The numerical value for logarithm to the base 10 can be calculated with the following identity.


    Since Math.log(x) in JavaScript returns the natural logarithm of x (same as ln(x)), for base 10 you can divide by Math.log(10) (same as ln(10)):

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

    Math.LN10 is a built-in precomputed constant for Math.log(10), so this function is essentially identical to:

    function log10(val) {
      return Math.log(val) / Math.log(10);
    }
    
    0 讨论(0)
提交回复
热议问题