0

I need to use something like logb from C++ but Google searches turn up absolutely nothing useful and I'm having trouble understanding how to replicate the function based on that C++ document.

Does anyone know how to make a polyfill or equivalent function for JS?

user0042
  • 7,917
  • 3
  • 24
  • 39

1 Answers1

1

From the document you linked

Returns the logarithm of |x|, using FLT_RADIX as base for the logarithm.

On most platforms, FLT_RADIX is 2, and thus this function is equivalent to log2 for positive values.

So you just need to compute whats the log2(|x|).

Math.log(Math.abs(x))/Math.log(2)

Logarithmic functions have a base, the most common one is 10 since we work in a base 10 numeric system. Common bases for computers is a base 2 since it works in a binary system. Converting bases can be simply done by working with this formula.

Logb(x) = Logv(x) / Logv(b)

Simply take the Log(x) in any base you want (10 for instance) and divide it by the Log(b).

Heres a relevant link about it:

http://www.mathwords.com/c/change_of_base_formula.htm https://www.khanacademy.org/math/algebra2/exponential-and-logarithmic-functions/change-of-base-formula-for-logarithms/a/logarithm-change-of-base-rule-intro

You might right a function like:

// get the log value of x using base b
function logb(x, b) {
  return Math.log(x)/Math.log(b);
}
ug_
  • 11,267
  • 2
  • 35
  • 52
  • Hmm, in [the context I'm trying to replicate](https://stackoverflow.com/a/46996648/5536767), the person inputs two numbers to `logb` like [this](https://gist.github.com/viziionary/6bc20c1a459ee960255abc6a670125b9) maybe you could explain how I could make a `logb` version which accepts two inputs? –  Oct 29 '17 at 04:38
  • @Viziionary the gist you linked to doesn't show the function, and the original one doesn't seem to say anything about a 2nd param. However I updated my answer with what *I think* the 2nd param would be and about it. – ug_ Oct 29 '17 at 04:50