[英]Translating a float to a negative or positive
I have a float
from 0 to 100
and I want to translate that into a number from -20 to 20
an example: 我有一个从0 to 100
的float
,我想将其转换为一个从-20 to 20
的数字,例如:
float
is 100
then translated it would be -20
float
是100
然后翻译为-20
float
is 50
then translated it would be 0
float
是50
然后翻译为0
float
is 0
then translated it would be 20
float
为0
然后翻译为20
What is the best method of doing this? 最好的方法是什么?
[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. 您需要一个线性变换,形式为y = mx + c
,其中x
是您的输入数字, y
是您的输出数字,并且m
和c
是您需要提前确定的常数。
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. 我可以选两个。
怎么样: (50. - x) * 0.4
这样的事情应该做:
20 - val * 0.4
float procent = (myval - 50)/2.5f;
如果需要整数,请使用(int) floor(procent)
...
float translate(float f)
{
return 20.0f - ((20.0f * f) / 50.0f);
}
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): 在您的情况下,您可以这样称呼(用您的值替换x):
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. 有关参考文章,请参见http://en.wikipedia.org/wiki/Linear_interpolation 。
((x / 2.5)- 20) * -1
这应该做
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. 由于您已经有3个点(0,-20)(50,0)(100,20),因此可以执行dx = 40/100 = 2/5(y的变化/ x的变化)和b = -20。 Then you define a function (f(x) = mx + b) f(x) = (2/5)*x - 20, 0 <= x <= 100. 然后定义一个函数(f(x)= mx + b)f(x)=(2/5)* x-20,0 <= x <= 100。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.