diff --git a/src/main/common/maths.c b/src/main/common/maths.c index 4b329e61c..97fc28679 100644 --- a/src/main/common/maths.c +++ b/src/main/common/maths.c @@ -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 diff --git a/src/main/common/maths.h b/src/main/common/maths.h index 807be800b..a7839a4c4 100644 --- a/src/main/common/maths.h +++ b/src/main/common/maths.h @@ -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); diff --git a/src/test/unit/maths_unittest.cc b/src/test/unit/maths_unittest.cc index 0a20fd63c..64aa6736a 100644 --- a/src/test/unit/maths_unittest.cc +++ b/src/test/unit/maths_unittest.cc @@ -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