Potassium Ion
Potassium Ion

Reputation: 2185

Custom Logarithm Lua (Answer has trick that can be used on almost any language)

I'm working on a base converter for lua that can convert the base of any number to another base. For that, I need a logarithm calculator. Example function (where logarithm(100, 10) would equal log10(100), which would equal 2):

function logarithm(value, base)
    ... -- Algorithm here
end
print(logarithm(100, 10))

Which would output:

2

P.S: I want the algorithm to accept any base, any value.

Upvotes: 4

Views: 5302

Answers (2)

darkfrei
darkfrei

Reputation: 566

for example math.log2 can be done as

math.log2 = function (x)
    return math.log(x) / math.log(2)
end

Upvotes: 0

Lutz Lehmann
Lutz Lehmann

Reputation: 26040

You can always use that

logb(a) = logc(a) / logc(b)

where c is one of the provided bases, like the Euler number e of the natural logarithm or 10, sometimes also the basis 2 logarithm is provided.

Upvotes: 12

Related Questions