Made 'scaleRange' agnostic to order of ranges.

This commit is contained in:
Michael Keller 2017-04-07 18:39:57 +12:00
parent d6de0c9e24
commit edc44bd830
3 changed files with 25 additions and 6 deletions

View File

@ -152,10 +152,10 @@ float degreesToRadians(int16_t degrees)
return degrees * RAD;
}
int scaleRange(int x, int srcMin, int srcMax, int destMin, int destMax) {
long int a = ((long int) destMax - (long int) destMin) * ((long int) x - (long int) srcMin);
long int b = (long int) srcMax - (long int) srcMin;
return (a / b) + destMin;
int scaleRange(int x, int srcFrom, int srcTo, int destFrom, int destTo) {
long int a = ((long int) destTo - (long int) destFrom) * ((long int) x - (long int) srcFrom);
long int b = (long int) srcTo - (long int) srcFrom;
return (a / b) + destFrom;
}
// Normalize a vector

View File

@ -85,7 +85,7 @@ float devVariance(stdev_t *dev);
float devStandardDeviation(stdev_t *dev);
float degreesToRadians(int16_t degrees);
int scaleRange(int x, int srcMin, int srcMax, int destMin, int destMax);
int scaleRange(int x, int srcFrom, int srcTo, int destFrom, int destTo);
void normalizeV(struct fp_vector *src, struct fp_vector *dest);

View File

@ -70,7 +70,7 @@ TEST(MathsUnittest, TestScaleRangeNegatives)
EXPECT_EQ(scaleRange(-50, -100, 0, -10, 0), -5);
}
TEST(MathsUnittest, TestScaleRangeReverse)
TEST(MathsUnittest, TestScaleRangeNegativePositive)
{
// Within bounds
EXPECT_EQ(scaleRange(0, -10, 0, 0, 100), 100);
@ -89,6 +89,25 @@ TEST(MathsUnittest, TestScaleRangeReverse)
EXPECT_EQ(scaleRange(-50, -100, 0, 0, 10), 5);
}
TEST(MathsUnittest, TestScaleRangeReverse)
{
// Within bounds
EXPECT_EQ(scaleRange(0, 0, 10, 100, 0), 100);
EXPECT_EQ(scaleRange(10, 0, 10, 100, 0), 0);
EXPECT_EQ(scaleRange(0, 0, 100, 10, 0), 10);
EXPECT_EQ(scaleRange(100, 0, 100, 10, 0), 0);
// Scale up
EXPECT_EQ(scaleRange(1, 0, 10, 100, 0), 90);
EXPECT_EQ(scaleRange(2, 0, 10, 100, 0), 80);
EXPECT_EQ(scaleRange(5, 0, 10, 100, 0), 50);
// Scale down
EXPECT_EQ(scaleRange(10, 0, 100, 10, 0), 9);
EXPECT_EQ(scaleRange(20, 0, 100, 10, 0), 8);
EXPECT_EQ(scaleRange(50, 0, 100, 10, 0), 5);
}
TEST(MathsUnittest, TestConstrain)
{
// Within bounds