Level calculation based on total experience points

497 Views Asked by At

I am running into an issue when it comes to calculating a player's level based on the total experience points they have. I came up with this formula for calculating XP needed for each level

 EXP_PER_LEVEL =  75*(CURRENT_LEVEL-1) + 200

So it takes 75*0+200 to reach level 2 (200 xp)

and 875 XP to reach level 11 (75*(10-1)+200)

This is the formula for calculating TOTAL XP from player's level

 TOTAL_XP =  37.5*(pow(CURRENT_LEVEL, 2)) + 87.5*CURRENT_LEVEL - 125;

Now I have problem with the reversal formula. In simple terms, based on these formulas, how would I calculate the player's level by just using the experience points they have ? Could you provide a math example of how it would work?

1

There are 1 best solutions below

5
On BEST ANSWER

It sounds like you want to solve the following equation for $x$, where $x$ represents the level and $y$ represents the total experience points: $$ y = \frac{75}2 x^2 + \frac{175}2 x - 125 $$

First subtract $y$ from both sides: $$ 0 = \frac{75}2 x^2 + \frac{175}2 x - 125 - y $$

Then multiply both sides by $2$ to simplify things. Not a necessary step, but it'll help simplify a little. $$ 0 = 75 x^2 + 175 x - 250 - 2y $$

Now use the quadratic formula, $x = \dfrac{-b \pm \sqrt{b^2 - 4ac}}{2a}$, where $a$, $b$, and $c$ are as follows: $$ 0 = \underbrace{75}_a x^2 + \underbrace{175}_b x \underbrace{- 250 - 2y}_c $$

To be clear: \begin{align*} a &= 75\\ b &= 175\\ c &= -250 - 2y \end{align*}

Finally, take only the positive root, i.e., $$x = \frac{-b + \sqrt{b^2 - 4ac}}{2a}$$ (explained below) and then you'll want to round your answer down to the nearest integer (also explained below).


Untested PHP code snippet example:

$y = 1100;  // 1100 total experience points
$a = 75;
$b = 175;
$c = -250 - 2 * $y;

$x = (-$b + sqrt($b * $b - 4 * $a * $c)) / (2 * $a);  // $x is about 4.667
$x = floor($x);  // Always round down.  Player is level 4 in this example.

Explanation:

The quadratic formula actually gives us two roots because of the $\pm$ sign in the numerator: $$ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$

But for this application we only want the $+$ sign. This is because $x$ must be positive since it represents the player's current level, but if we take the root with the $-$ sign then we'll (always) get a negative number.

This example also highlights why we always want to round down. If we rounded $4.667$ up as per the standard rounding rules, then we would get $x=5$, which means the player is level 5, but according to the total XP formula, the player can't be level 5 until the player has 1250 XP: $$ 37.5 \cdot 5^2 + 87.5 \cdot 5 - 125 = 1250 $$

In other words, a player hasn't actually reached level 5 until the player is actually at level 5. Therefore being "close" to level 5 (e.g., being at "level 4.667") doesn't count as being at level 5.