admin管理员组文章数量:1432627
According to Google Test's documentation about floating point comparison, EXPECT_DOUBLE_EQ
and ASSERT_DOUBLE_EQ
verify that the two double values val1
and val2
are approximately equal, to within 4 ULPs (Units in the Last Place) from each other.
The following code example, however, fails the test even though the difference in the two doubles occur in 2 ULPs.
TEST(Foo, doubles_match)
{
ASSERT_DOUBLE_EQ(0.62469504755442462, 0.62469504755442407);
}
Results:
error: Expected equality of these values:
0.62469504755442462
0.62469504755442407
What am I missing?
According to Google Test's documentation about floating point comparison, EXPECT_DOUBLE_EQ
and ASSERT_DOUBLE_EQ
verify that the two double values val1
and val2
are approximately equal, to within 4 ULPs (Units in the Last Place) from each other.
The following code example, however, fails the test even though the difference in the two doubles occur in 2 ULPs.
TEST(Foo, doubles_match)
{
ASSERT_DOUBLE_EQ(0.62469504755442462, 0.62469504755442407);
}
Results:
error: Expected equality of these values:
0.62469504755442462
0.62469504755442407
What am I missing?
Share Improve this question asked Nov 18, 2024 at 21:08 Constantinos GlynosConstantinos Glynos 3,2062 gold badges17 silver badges33 bronze badges 4 |1 Answer
Reset to default 0The numbers mentioned in the question are 5 ULPs apart (considering binary 64-bit IEEE-754 numbers). You can verify this with this program:
#include <bit>
#include <cstdint>
#include <print>
int main() {
const std::uint64_t a = std::bit_cast<std::uint64_t>(0.62469504755442462);
const std::uint64_t b = std::bit_cast<std::uint64_t>(0.62469504755442407);
std::print("{:016x}\n", a);
std::print("{:016x}\n", b);
std::print("diff: {}\n", a - b);
}
It outputs:
3fe3fd8077e7057a
3fe3fd8077e70575
diff: 5
本文标签: cASSERTDOUBLEEQ fails on 2 ULPsStack Overflow
版权声明:本文标题:c++ - ASSERT_DOUBLE_EQ fails on 2 ULPs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745594287a2665381.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
0.6246950475544246206283105493639595806598663330078125
and0.62469504755442406551679823678568936884403228759765625
is0.00000000000000055511151231257827021181583404541015625
, which is 5 ULPs. You can count the number of steps needed usingstd::nextafter
. Unless I'm on a different page for what ULPs means in this context. – Eljay Commented Nov 18, 2024 at 21:26a
format is also helpful for checking exact mantissa values (or transferring them between programs reliably as text). – Martin Brown Commented Nov 18, 2024 at 22:18