Help finding inverse XP function

Started by
2 comments, last by mr_malee 7 years, 2 months ago

Hi, so I've got a function that gives me a XP for a given level.

I'm looking at finding the inverse: (Level from XP)

e.g:


int GetXPForLevel(int level) {

	float baseXP = 100;
	float xp = (Mathf.Pow(level, 2) + level) / 2 * baseXP - (level * baseXP);

	return Mathf.FloorToInt(xp);
}

int GetLevelForXP(int xp) {

	//need the inverse of the above function

	return 0;
}

My Math skills are not great :(, not sure where to even begin

Advertisement
Simplifying your code, you have

xp = 50 * level * level - 50 * level

Solving the quadratic equation,

level = (50 + sqrt(50 * 50 + 4 * 50 * xp)) / 100


So for instance, if you plug first compute xp = 50 * 15 * 15 - 50 * 15 = 10500, you can then recover

((50 + sqrt(50 * 50 + 4 * 50 * 10500)) / 100 = 15

EDIT: Fixed some silly mistake. That's what I get for answering questions at night after a long day. :)

Really appreciate the help, I must be stupid, but how did you get 15 out of that equation? I get 750


float a = 50;
float b = Mathf.Sqrt(50 * 50 + 4 * 50 * 10500); //1450
float c = (a + b) / 2; //750

I got it working. Thanks again for the help


int GetLevelForXP(int xp) {

	float baseXP = 100;

	float a = baseXP / 2f;
	float b = Mathf.Sqrt(a * a + 4 * a * xp) / a;
	float c = b / 2f;

	int level = Mathf.CeilToInt(c);

	//because of rounding issues the level returned might be higher. So check and reduce if necessary
	//the XP at the level returned should always be <= to the input level

	while (GetXPForLevel(level) > xp) {

		level--;
	}

	return level;
}

This topic is closed to new replies.

Advertisement