Linear Interpolation Problem

Hello, I have the following problem.

How can I interpolate from a given value A to a value B relative to a given initial value X to a end value Y

where A = 0, B = 100

and X = 0.1 and Y=0

In other words:

When my input is 0.1, my output is 0
When my input is 0, my output is 100

Mathematically:
f(0.1) = 0
f(0) = 100
I need to find the function f

I think the solution is LERP but I dont know how to use it for this, and maybe is not even lerp.

Thanks for your help.

The answer is indeed Mathf.Lerp but you have to scale your particular input first.

The way Mathf.Lerp( a, b, c) works, it will give you a value between a and b depending on the value of c ranging from 0.0 to 1.0

Since your input is 0.1 to 0.0, you can scale that to be 0 to 1 by inverting and scaling it:

float alpha = (0.1f - input) * 10.0f

That will make alpha be from 0 to 1 as long as input goes from 0.1 to 0.0.

Then your result is just

float result = Mathf.Lerp( 0.0f, 100.0f, alpha);
1 Like

That is an awesome response, Thanks a lot

I see that normalizing the value from 0.1 to 0 is easy in this case, is there a method to find this normalization formula for arbitrary values?

Lets say those are defined at runtime

Generally if a value goes from A to B, and A and B are different values, you can rescale that value to range from 0 to 1 with the following formula:

float output = (input - A) / (B - A);

Substituting to the above reply I made, you get

float output = (input - 0.1f) / (0.0f - 0.1f);

or…

float output = (input - 0.1f) / -0.1f;

or…

float output = (0.1f - input) / 0.1f;

or…

float output = (0.1f - input) * 10f;

Math is cool. If I’m lucky I didn’t screw any of that math up. I’m sure someone will let me know if I did! Good night.

That is perfect! Thanks a lot.
I was wondering where that 10 came from, I didnt noticed it was the inverse of 1/10

Thanks again for your help. Good Night

1 Like