Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would you create a log a(b) algorithm in Lua?

I'm trying to make a system of diminishing returns by using a logarithmic algorithm, but I don't know how to make that in Lua. I have come up with this...

local startNumber = a
local goalNumber = b
local outcome = 1
 
while startNumber < goalNumber do
	outcome = outcome + 1
        startNumber = startNumber * a
end
	 
print(outcome)

but obviously, this code has some flaws.

log2(1) would give 1 when it's supposed to give 0,

local2(10) would give 4 when it's supposed to give something around 3.32,

and the faulty outcomes continues...

Any ideas of how mo make it accurate no matter what I put in?

1 answer

✓ Accepted answer

Question

How would you create a log a(b) algorithm in Lua?

Answer

Just use the log change base rule.

This states that log_b(a) = log_x(a)/log_x(b)

For more information on this check out this video: https://www.youtube.com/watch?v=pZqDXF-hA18

Lua's implementation of log is base e but this is fine since it is constant. We can create a logn by using the change base method.

--// n representing the base, x representing the number to take the log of

local function logn(n, x)
	return math.log(x) / math.log(n)
end

print(logn(25, 5)) --// outputs .5

So, this (logn(25, 5)) is equivalent to the 25th log of 5 (which is .5 because 25^.5 is 5)

This discussion is preserved as it was. New answers, comments, and votes are closed.