Reputation: 2275
I have a float
from 0 to 100
and I want to translate that into a number from -20 to 20
an example:
float
is 100
then translated it would be -20
float
is 50
then translated it would be 0
float
is 0
then translated it would be 20
What is the best method of doing this?
Upvotes: 1
Views: 224
Reputation:
You need to calculate the slope. Since you have already 3 points (0, -20) (50, 0) (100, 20), you can do dx = 40/100 = 2/5 (change in y / change in x) and b = -20. Then you define a function (f(x) = mx + b) f(x) = (2/5)*x - 20, 0 <= x <= 100.
Upvotes: 0
Reputation: 7164
What you want to achieve is called "Linear interpolation" and can be done in a general function like this:
float linear_interpolate(float x, float x0, float x1, float y0, float y1)
{
return y0 + (x - x0)*((y1-y0)/(x1-x0));
}
In your case you would call it like (replace x with your in value):
float value = linear_interpolate(x, 0.0f, 100.0f, -20.0f, 20.0f);
See http://en.wikipedia.org/wiki/Linear_interpolation for a reference article.
Upvotes: 1
Reputation: 101494
float translate(float f)
{
return 20.0f - ((20.0f * f) / 50.0f);
}
Upvotes: 1
Reputation: 272717
[I'm going to give you the approach to figuring this out, rather than just the answer, because it'll be more useful in the long-run.]
You need a linear transform, of the form y = mx + c
, where x
is your input number, y
is your output number, and m
and c
are constants that you need to determine ahead of time.
To do so, you need to solve the following simultaneous equations:
-20 = m * 100 + c
+20 = m * 0 + c
Note that I've picked two of your required transformation examples, and plugged them into the equation. I could have picked any two.
Upvotes: 10
Reputation: 12554
float procent = (myval - 50)/2.5f;
use (int) floor(procent)
if you need integers...
Upvotes: 1