• Advertisement
Sign in to follow this  

Help finding inverse XP function

Recommended Posts

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

Share this post


Link to post
Share on other sites
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. :) Edited by �lvaro

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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;
}
Edited by mr_malee

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Advertisement