gtest (C++) 和 nunit (C#) 中双重比较之间的差异
我已经将带有 gtest 测试的 c++ 项目移植到带有 nunit 测试的 ac# 项目。现在我遇到浮点精度问题。
在 nunit 测试中,我的表现不太好(红色)
Assert.AreEqual(0.7, 7 * 0.1);
在 gtest 测试中,我的表现是:
ASSERT_DOUBLE_EQ(0.7, 7 * 0.1);
哪个没问题(绿色)
现在的问题是为什么???
I have done porting of a c++ project with gtest tests to a c# project having an nunit test. Now I encounter problems with floating point precision.
in the nunit test I have being not ok (red)
Assert.AreEqual(0.7, 7 * 0.1);
in the gtest test I have:
ASSERT_DOUBLE_EQ(0.7, 7 * 0.1);
which is ok (green)
The question now is WHY???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Google 测试的
ASSERT_DOUBLE_EQ()
验证实际值是否在预期值的 4 个 ULP 范围内(请参阅https://github.com/google/googletest/blob/main/docs/advanced.md#floating-point-comparison)。 Nunit 可能正在执行精确比较。Google Test's
ASSERT_DOUBLE_EQ()
verifies that the actual value is within 4 ULPs of the expected one (see more info at https://github.com/google/googletest/blob/main/docs/advanced.md#floating-point-comparison). Nunit is probably performing exact comparison.或者,您可以添加第三个参数,它是两个值之间的最大差异,您可以阅读 此处。
Alternatively you can add a third parameter, which is the maximum difference between the two values, as you can read here.
永远不要比较浮点数是否相等!十进制小数(如 0.1)无法在不损失少量精度的情况下表示为 IEEE 浮点数。看起来像 0.7 的可能是 0.6999999 或者其他的东西。那么它们是不同的数字。您应该使用 epsilon 技术:考虑
a == b if abs(a - b) <= epsilon
,其中 epsilon 是非常小的常数。阅读本文和其他许多内容^
http://docs.sun.com/source/ 806-3568/ncg_goldberg.html
有什么问题Java 中使用 == 比较浮点数?
never-ever compare floating point numbers for equality! decimal fractional numbers (like 0.1) can't be represented into ieee floats without small precision lost. what may look like 0.7 may be 0.6999999 or something else indeed. they are different numbers then. You should use epsilon technique: consider
a == b if abs(a - b) <= epsilon
, where epsilon is very small constant number.read this and many others^
http://docs.sun.com/source/806-3568/ncg_goldberg.html
What's wrong with using == to compare floats in Java?
在比较浮点数时尝试 Assert.AreApproximatelyEqual 。
Try Assert.AreApproximatelyEqual when comparing floats instead.