How can you perform various logarithmic functions of a base in Javascript?

This problem is posed considering the node.js server, but I asked the question as "javascript" because I will most likely use the same logic for the client side of the script.

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

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

log[512](2)

Which should return .1111 ~

However, I do not see the interface that allows me to do this, and I cannot find a library that provides an opportunity for the log database. Of course, this is a common problem and has a solution, but my search found solutions only for different / unrelated problems. Ideas?

+4
source share
2 answers

You can use the logarithm database change formula :

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

So, 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 a natural log base; those. it will be mathematically written as ln .

+14
source

I found this answer as the first result on google today, and if anyone else finds it, there is a small error. The correct version is as follows:

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

Source: https://habr.com/ru/post/1386144/


All Articles