Javascript Math log()

Introduction

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

The JavaScript Math.log() function is equivalent to ln(x) in mathematics.

Math.log(x) // x  is a number.

If the value of x is 0, the return value is always -Infinity.

If the value of x is negative, the return value is always NaN.

To calculate the natural log of 2 or 10, use the constants Math.LN2 or Math.LN10.

To calculate a logarithm to base 2 or 10, use Math.log2() or Math.log10().

To calculate a logarithm to other bases, use Math.log(x)/Math.log(otherBase).

let a = Math.log(-1); // NaN, out of range
console.log(a);/*w  ww  .j  a v a 2s . c o m*/
a = Math.log(0);  // -Infinity
console.log(a);
a = Math.log(1);  // 0
console.log(a);
a = Math.log(10); // 2.302585092994046
console.log(a);

Math.log() with different base

The following function returns the logarithm of y with base x:

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

let a = getBaseLog(10, 1000);
console.log(a);/*from   w  ww.  j  a  va2 s.c  o  m*/



PreviousNext

Related