CIA
CIA

Reputation: 302

Why is my javascript returning an incorrect value for Math.log?

My script:

var dblTemp = 365 * 24 * 60 * 60 * 12000000000; //378432000000000000

return Math.log(dblTemp);

My expected value is ~17.5779878529829. I derive this by using my Windows Calculator to enter 378432000000000000 then press the log function.

If I run my script, it returns ~40.47481279510905.

Am I using Math.log incorrectly? Why is my javascript returning an incorrect value for Math.log?

Upvotes: 0

Views: 300

Answers (2)

joews
joews

Reputation: 30330

Your calculator calculates the base 10 logarithm. Math.log calculates the base e logarithm.

If you want the same result as your calculator, use Math.log10:

var dblTemp = 365 * 24 * 60 * 60 * 12000000000; //378432000000000000

document.write(Math.log10(dblTemp));

If your runtime doesn't support Math.log10 you can define the function yourself:

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

Math.LN10 is supported by all browsers.

Upvotes: 2

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

Because Math.log() uses a base of e while your calculator is using base 10. So you want to use Math.log10:

return Math.log10(dblTemp); // 17.577987852982993

Upvotes: 0

Related Questions