Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you perform varying base logarithmic functions in Javascript?

This problem is being asked with a node.js server in mind, but I stated the question as "javascript" because I will likely use this same logic for a client-side script, as well.

Here's the problem: given a set of x values, y needs to scale in a logarithmic way. The Math object performs a natural log [ln(x)], but does not provide an interface for specifying the base of the logarithm.

For a specific example, I need to find the following:

log[512](2)

Which should return .1111~

However, I do not see an interface that allows me to accomplish this, nor can I seem to find a library that exposes an option for the log's base. Surely this is a common problem and has a solution, but my searching has only found solutions for different/unrelated problems. Ideas?

like image 776
Aejay Avatar asked Dec 13 '11 16:12

Aejay


People also ask

How do you do log base 2 in JavaScript?

The log2() function returns the base-2 logarithm of a number. If the number is 0, the log2() function will return -Infinity. If the number is a negative value, the log2() function will return NaN.

What is log () method in JavaScript?

log() method returns the natural logarithm (base E) of a number.

Which function returns the logarithm of a number to a specified base?

Log(Double, Double) Returns the logarithm of a specified number in a specified base.


1 Answers

You can use the logarithm base change formula:

log[a](n) = log[b](n) / log[b](a)

So in order to get log(2) base 512, use:

function log(b, n) {
    return Math.log(n) / Math.log(b);
}

alert(log(2, 512));

Note that Math.log above uses the natural log base; i.e., it would be written as ln mathematically.

like image 138
Platinum Azure Avatar answered Oct 16 '22 05:10

Platinum Azure