C# .Net 双问题... 6.8 != 6.8?
我在工作中进行了一些单元测试,其中一个断言出现了一个特殊的错误。请注意,expectedValue 和actualValue 都是双精度值。
Assert.AreEqual(expectedValue, actualValue);
例外情况表明它们不相等,并详细说明了“期望值:<6.8>;实际值:<6.8>”。
预期值是硬编码的 6.8,实际值是使用数据库值通过我们的分类方法(例如 Equal Records 或 Jenks Natural Breaks)制定的。
我的猜测是,差异可能在于两个值的尾数直到最低有效位为止都相似。我更新了测试以包含 epsilon 来查找这两个值是否足够接近,但我很好奇是否有一种方法可以强制尾数与我显示该双精度的显示值匹配。这样的尾数修正是否存在?
I was doing some unit testing at work and a peculiar error popped up for one of the assertions. Note that expectedValue and actualValue are both doubles.
Assert.AreEqual(expectedValue, actualValue);
The exception stated that they were not equal, elaborating that "expected value: <6.8> actual value: <6.8>."
The expected value is a hard coded 6.8 and the actual value is formulated using database values going through our classification methods (such as Equal Records, or Jenks Natural Breaks).
My guess is that the difference is probably that the mantissas of the 2 values are similar up until the least significant bit. I updated the tests to include an epsilon to find if the two values are close enough, but I'm curious to if there is a way to force the mantissa to match with the display value of if I displayed that double. Does such a mantissa correction exist?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不完全确定强制尾数与显示值匹配是什么意思...例如,没有恰好为 0.1 的双精度值。
但是,如果您希望某些代码显示双精度值的精确,我有一个 DoubleConverter.cs 文件,这使得事情变得简单:
另一种选择是在将双精度数转换为字符串时使用往返格式说明符(“r”) - 这保证结果有足够的信息来重现稍后会得到相同的精确值。换句话说,如果
x != y
,则x.ToString("r") != y.ToString("r")
。I'm not entirely sure what you mean by forcing the mantissa to match the display value... there are no double values which are exactly 0.1, for example.
If you want some code to display the exact value of a double, however, I have a DoubleConverter.cs file which makes it easy:
Another alternative is to use the round-trip format specifier ("r") when converting a double to string - that guarantees that the result has enough information to reproduce the same exact value later. In other words, if
x != y
, thenx.ToString("r") != y.ToString("r")
.您可以将两者都转换为字符串:
actualValue.ToString("0.000")
并比较这些字符串。这可以非常符合您的要求。
You could convert both to a string :
actualValue.ToString("0.000")
and compare those strings.That could be made to match your requirements closely.
如果要测试默认显示值是否匹配,只需比较默认显示值即可:
If you want to test whether the default display values match, just compare the default display values: