JasonWyatt

This blog is full of stuff, and things.

Find my resume.

permalink

Natural Log in JavaScript

If you need to take the natural log (a.k.a. “ln”) of a value in JavaScript, you might at first be disheartened to learn there is no such thing as Math.ln() - only Math.log(). However, if you remember way back to high school mathematics, you can use the following identity to calculate logarithms of any base via any other base:

Logb(x) = Loga(x) / Loga(b)
Since the natural log has a base of e and the basic verson of Math.log uses a base of 10, we need to do the following:
Ln(x) = Loge(x) = Log10(x) / Log10(e)
In JavaScript, this becomes:
function ln(val){
    return Math.log(val) / Math.log(Math.E);
}
We can optimize it, however, by using a built-in constant from the Math object so we don’t need to calculate Math.log(Math.E) every time we need to take the natural log of a value:
function ln(val){
    return Math.log(val) / Math.LOG10E;
}

blog comments powered by Disqus