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?
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.
log() method returns the natural logarithm (base E) of a number.
Log(Double, Double) Returns the logarithm of a specified number in a specified base.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With