Mathematical problem
-
26-09-2019 - |
Question
I have the following function:
function getLevel(points)
{
var level = -1 + Math.sqrt(4 + points/20);
// Round down to nearest level
return Math.floor(level);
}
The above function calculates the level of a player based on their points, my problem is that I need a function like this to calculate the points needed for a given level.
Solution
Math.sqrt(4 + points/20) = level + 1
4 + points/20 = (level + 1)^2
points/20 = (level + 1)^2 - 4
points = 20 * ((level + 1)^2 - 4)
= 20 * ((level^2 + 2*level + 1) - 4)
= 20 * ( level^2 + 2*level - 3 )
= 20 * level^2 + 40*level - 60
OTHER TIPS
The inverse of that function would be:
points = ((level + 1)**2 - 4) * 20
(where **
is the power operator).
level = -1 + (4 + points / 20) ** 0.5
level + 1 = (4 + points / 20) ** 0.5
(level + 1) ** 2 = 4 + points / 20
(level + 1) ** 2 - 4 = points / 20
20 * ((level + 1) ** 2 - 4) = points
Should be fairly easy, just solve for points:
level = -1 + Math.sqrt(4 + points / 20)
level + 1 = Math.sqrt(4 + points / 20)
Math.pow(level + 1, 2) = 4 + points / 20
Math.pow(level + 1, 2) - 4 = points / 20
20 * (Math.pow(level + 1, 2) - 4) = points
So:
points = 20 * (Math.pow(level + 1, 2) - 4)
20(L+1)2 - 80
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow