I am unable to understand why the test case failed in case of summing double numbers or floats. It works very finely for the integer data type.
//the method in simple_method.h
double sum ( double a, double b)
{
double res = a+b;
return res;
}
// the test case for this method
TEST(simpleSum, sumOfFloat)
{
EXPECT_EQ(4.56, sum(0.56, 4.0));
}
// the output is
Running main() from gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from simpleSum
[ RUN ] simpleSum.sumOfFloat
/home/pcadmin/Desktop/so/so3/simple_method_test.cpp:7: Failure
Value of: sum(0.56, 4.0)
Actual: 4.56
Expected: 4.56
[ FAILED ] simpleSum.sumOfFloat (0 ms)
[----------] 1 test from simpleSum (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] simpleSum.sumOfFloat
1 FAILED TEST
And the reason the comparison succeeds with 1.5 is that 1.5 can be represented exactly as a float and as a double ; it has a bunch of zeros in its low bits, so when the promotion adds zeros the result is the same as the double representation.
Double is more precise than float and can store 64 bits, double of the number of bits float can store. Double is more precise and for storing large numbers, we prefer double over float.
Float has to round more than double, because it is smaller, so 1.1 rounded to the nearest valid Float is different to 1.1 rounded to the nearest valud Double.
Use EXPECT_NEAR
or the DoubleEq
matcher instead. Floating point operations can lead to rounding errors which makes the results ever so slightly different.
See documentation for Floating Point Comparison
EXPECT_EQ
uses exact match.
But you cannot match two floating numbers exactly. (at least with ease.)
You can use EXPECT_FLOAT_EQ
or EXPECT_DOUBLE_EQ
. (with heuristic bounds)
Also, you may use EXPECT_NEAR
with specific bounds.
From https://testing.googleblog.com/2008/10/tott-floating-point-comparison.html
When comparing floating-point values, checking for equality might lead to unexpected results. Rounding errors can lead to a result that is close to the expected one, but not equal. As a consequence, an assertion might fail when checking for equality of two floating-point quantities even if the program is implemented correctly.
The Google C++ Testing Framework provides functions for comparing two floating-point quantities up to a given precision.
ASSERT_FLOAT_EQ(expected, actual);
ASSERT_DOUBLE_EQ(expected, actual);
EXPECT_FLOAT_EQ(expected, actual);
EXPECT_DOUBLE_EQ(expected, actual);
In your case,
TEST(simpleSum, sumOfFloat)
{
EXPECT_DOUBLE_EQ(4.56, sum(0.56, 4.0));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With