Home > OS >  Reversing exponents in lua
Reversing exponents in lua

Time:11-03

I have a algorithm to calculate the desired exp for reach a level. But I didn't know how get the desired level based on his EXP.

local function NextLevelXP(level)
    return math.floor(1000 * (level ^ 2.0))
end
print(NextLevelXP(7)) -- output: 49000

Now I want the level based on his EXP, with something like:

local function MagicFunctionThatWillLetMeKnowTheLevel(exp)
   return --[[math magics here]]
end
print(MagicFunctionThatWillLetMeKnowTheLevel(49000)) --output: 7
print(MagicFunctionThatWillLetMeKnowTheLevel(48999)) --output: 6

I've tried some worse and weird algorithms, but no success.

CodePudding user response:

This can be simplified:

local function NextLevelXP(level)
    return math.floor(1000 * (level ^ 2.0))
end

the math.floor is not necessary if level will always be an integer.

to reverse the formula you can do:

local function CurrentLevelFromXP(exp)
    return math.floor((exp / 1000) ^ (1/2))
end

Here it is necessary to floor the value as you will get values between levels, (like 7.1, 7.5, 7.8). To reverse the multiplication by 1000 we divide by 1000, to reverse the exponent we use the inverse of the exponent, in this case 2 becomes 1/2 or 0.5


Also, as a special case, for ^2 you can simply math.sqrt the value.

  • Related