float scale(float value, float minA, float maxA, float minB, float maxB)
{
// compute scaling factor:
float rangeA = maxA - minA; // dx
float rangeB = maxB - minB; // dy
float slope = rangeB / rangeA; // m
float intercept = minB - slope * minA; // b
// compute value in new range:
float result = value * slope + intercept; // f(x)=m*x+b
// cut the new value if it is out of bounds:
if(result > maxB) result = maxB;
if(result < minB) result = minB;
return result;
}
This rather simple function linearly scales a value within range [minA, maxA] to a new range [minB, maxB].
Application Example
Let's say you want to have sensor readings within range [0°, 180°] of a laser scanner, but you want to store the data within the range [-1,1] because you let the laser scan a 180° field and 90° means straight ahead; you want that direction to be at 0. So you just call
scale(value, 0, 180, -1, 1) for an incomming sensor reading value and get the scaled one.
Inline Version
float scale(float value, float minA, float maxA, float minB, float maxB)
{
// compute value in new range and cut if out of bounds:
float slope = (maxB - minB) / (maxA - minA);
float v = value * slope + minB - slope * minA;
return v > maxB ? maxB : (v < minB ? minB : v);
}
Keine Kommentare:
Kommentar veröffentlichen