Why does assertAlmostEqual(-inf,-inf) fail?
Numpy's log method gives -inf for log(0). This value is comparable:
>>> np.log(0) == np.log(0)
True
Now in unittesting the f开发者_如何转开发ollowing 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?
From the doc of unittest assertAlmostEqual(a, b) is by default equivalent to round(a-b, 7) == 0
. so in your case you have :
In [8]: np.log(0) - np.log(0)
Out[8]: nan
In [9]: round(np.log(0) - np.log(0), 7)
Out[9]: nan
In [11]: np.nan == 0
Out[11]: False
That explain why your test fail.
For making it work use unittest2 here is an example:
import unittest2
import numpy as np
class Test_Assertions(unittest2.TestCase):
def test_float_inf(self):
self.assertAlmostEqual(float('inf'), float('inf'))
def test_numpy_inf(self):
self.assertAlmostEqual(np.log(0),np.log(0))
unittest2.main()
Output:
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
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 :)
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:
if valueA != valueB:
self.assertAlmostEqual(valueA, valueB)
精彩评论