为什么assertAlmostEqual(-inf,-inf) 失败?
Numpy 的 log 方法为 log(0) 提供 -inf。这个值是可比的:
>>> np.log(0) == np.log(0)
True
现在在单元测试中,以下工作正常:
self.assertEqual(np.log(0),np.log(0))
但这失败了:
self.assertAlmostEqual(np.log(0),np.log(0))
为什么这种行为是这样的?这是一个错误还是有意为之?如果有意的话,如何检查两个浮点值几乎相等,并且对于 -inf 也能正常工作?
Numpy's log method gives -inf for log(0). This value is comparable:
>>> np.log(0) == np.log(0)
True
Now in unittesting the following works fine:
self.assertEqual(np.log(0),np.log(0))
but this fails:
self.assertAlmostEqual(np.log(0),np.log(0))
Why is this behaviour like this? Is this a bug or intended? If intended, how can I check two float values to be almost equal, working also correctly for -inf?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自unittest assertAlmostEqual(a, b) 的文档是默认相当于
round(ab, 7) == 0
。所以在你的情况下你有:这解释了你的测试失败的原因。
为了使其工作,请使用 unittest2 这是一个示例:
Output:
NB: In unittest2
assertAlmostEqual ()
首先测试两个对象是否相等,如果是,则结果为是,否则执行魔法(几乎相等),这就是它起作用的原因。它也应该在新的 python 版本(2.7 >)中工作,因为它们中的大多数都实现了 unittest2 功能(我不确定这一点,因为我的工作站中没有 python 2.7 >)。希望这能有所帮助:)
From the doc of unittest assertAlmostEqual(a, b) is by default equivalent to
round(a-b, 7) == 0
. so in your case you have :That explain why your test fail.
For making it work use unittest2 here is an example:
Output:
N.B: In unittest2
assertAlmostEqual()
first test if the two objects are equal if yes so the result is yes else do the magic (almost equal) , this is why it work . It also should work in new python version (2.7 >) because most of them have the unittest2 functionality implemented (i'm not sure about this because i don't have python 2.7 > in my work station).Hope this can help :)
Inf 和任何有限值之间的差异是 Inf 或 -Inf。这是 IEEE754 规范的一部分。由于
assertAlmostEqual
使用减法,这解释了这种行为。以下是 Intel x86 文档中有关 FSUB 的相关表格:
要解决您的问题,您将需要特殊的Inf 的案件处理。
The difference between an Inf and any finite value is either Inf or -Inf. That's part of the IEEE754 specification. Since
assertAlmostEqual
uses subtraction this explains the behaviour.Here's the relevant table from the Intel x86 documentation for FSUB:
To solve your problem you are going to need special case handling for Inf.
我想说-∞和-∞之间的差异可以达到∞。因此,它们并不是真正的“几乎平等”。
如果您想忽略这种特殊情况,那么这样的事情可能会有用:
I'd say that the difference between -∞ and -∞ can be as much as ∞. Therefore, they aren't really "almost equal".
If you want to ignore this special case, then something like this might be useful: