Skip to content
Advertisement

Logarithm Algorithm

I need to evaluate a logarithm of any base, it does not matter, to some precision. Is there an algorithm for this? I program in Java, so I’m fine with Java code.

How to find a binary logarithm very fast? (O(1) at best) might be able to answer my question, but I don’t understand it. Can it be clarified?

Advertisement

Answer

Use this identity:

logb(n) = loge(n) / loge(b)

Where log can be a logarithm function in any base, n is the number and b is the base. For example, in Java this will find the base-2 logarithm of 256:

Math.log(256) / Math.log(2)
=> 8.0

Math.log() uses base e, by the way. And there’s also Math.log10(), which uses base 10.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement