Index: cc/base/math_util_unittest.cc |
diff --git a/cc/base/math_util_unittest.cc b/cc/base/math_util_unittest.cc |
index 9d44fba8ac034b9a7637bff7e0f70408fef11ca4..d0532ae7b8f81b8308f7d9e2f23a46e259dd8340 100644 |
--- a/cc/base/math_util_unittest.cc |
+++ b/cc/base/math_util_unittest.cc |
@@ -384,5 +384,55 @@ TEST(MathUtilTest, RoundDownUnderflow) { |
EXPECT_TRUE(MathUtil::VerifyRoundDown<int16_t>(-123, 50)); |
} |
+TEST(MathUtilTest, AlmostEqualFloats) { |
+ // Two almost equal floats. |
+ float value1 = 7.33907556533813f; |
+ float value2 = 7.33907508850098f; |
+ |
+ EXPECT_TRUE(value1 != value2); |
+ |
+ int max_precision = std::numeric_limits<float>::digits10 - 1; |
+ |
+ // Check with all possible precisions, the almost equal floats (differing |
+ // by small magnitude of epsilon) are same. |
+ for (int i = 0; i <= max_precision; ++i) { |
+ float value1_rounded_to_same_precision = |
+ MathUtil::RoundToFixedPrecision(value1, i); |
+ float value2_rounded_to_same_precision = |
+ MathUtil::RoundToFixedPrecision(value2, i); |
+ EXPECT_TRUE(value1_rounded_to_same_precision == |
+ value2_rounded_to_same_precision); |
+ } |
+ |
+ // Check the same float with different precisions. Different values should |
+ // be returned. |
+ for (int i = 0; i <= max_precision; ++i) { |
+ for (int j = i + 1; j <= max_precision; ++j) { |
+ float value1_rounded_to_precision_i = |
+ MathUtil::RoundToFixedPrecision(value1, i); |
+ float value1_rounded_to_precision_j = |
+ MathUtil::RoundToFixedPrecision(value1, j); |
+ EXPECT_FALSE(value1_rounded_to_precision_i == |
+ value1_rounded_to_precision_j); |
+ } |
+ } |
+ |
+ // Different floats created by differing some magnitude of epsilon. |
+ float value3 = value1 + (10 * std::numeric_limits<float>::epsilon()); |
+ EXPECT_TRUE(value1 != value3); |
+ EXPECT_TRUE(MathUtil::RoundToFixedPrecision(value1, 2) == |
+ MathUtil::RoundToFixedPrecision(value3, 2)); |
+ |
+ // Check different floats. |
+ float value4 = 7.3f; |
+ float value5 = 7.4f; |
+ // Rounded to precision 0, should be equal. |
+ EXPECT_TRUE(MathUtil::RoundToFixedPrecision(value4, 0) == |
+ MathUtil::RoundToFixedPrecision(value5, 0)); |
+ // Rounded to precision 1, should not be equal. |
+ EXPECT_FALSE(MathUtil::RoundToFixedPrecision(value4, 1) == |
+ MathUtil::RoundToFixedPrecision(value5, 1)); |
+} |
+ |
} // namespace |
} // namespace cc |