I have a float number which represent percentage (0.0 to 100.0) %
float represent = 50.00; // fifty present, or half.
as an example: convert this number to a range from -2 to 2 thus: represent=0 will be represented as -2 represent=50 will be represented as 0 represen开发者_如何学JAVAt=100 will be represented as 2
EDIT: good simple answer from Orbling and friends, Still I am looking for something along the lines of : map(value, fromLow, fromHigh, toLow, toHigh) Is there a function in objective C to map such range for more complex values?
represent = (represent / 25.0f) - 2.0f;
This should do the trick:
define map(v, r1, r2, t1, t2)
{
norm = (v-r1)/(r2-r1);
return (t1*(1-norm) + t2*norm);
}
Explanation:
- norm is v scaled to a value between 0 and 1, related to r1 and r2.
- Next line is calculates the point between t1 and t2 using norm as percentage factor.
Example usage:
map (0, 0, 100, -2, 2) // 0 mapped to -2..2 in the range 0..100
-2.0
map (50, 0, 100, -2, 2) // 50 mapped to -2..2 in the range 0..100
0
map (100, 0, 100, -2, 2) // 100 mapped to -2..2 in the range 0..100
2.0
map (-90, -100, 20, -4, 2) // -90 mapped to -4..2 in the range -100..20
-3.5
精彩评论