Why does assertAlmostEqual (-inf, -inf) fail?

The Numpy 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 does this behavior look like this? Is this a mistake or a hint? If possible, how can I check the two values ​​of the float so that they are almost equal, is the correct operation for -inf?

+3
source share
3 answers

From the unittest document, assertAlmostEqual (a, b) is equivalent by default 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

This explains why your test fails.

To use it, use unittest2 :

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()

Conclusion:

..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

N.B: unittest2 assertAlmostEqual() , , , ( ), . python (2.7), unittest2 ( , python 2.7 > ).

, :)

+5

Inf - Inf -Inf. IEEE754. assertAlmostEqual , .

Intel x86 FSUB:

enter image description here

, Inf.

+4

, -∞ -∞ ∞. " ".

If you want to ignore this special case, then something like this might be useful:

if valueA != valueB:
  self.assertAlmostEqual(valueA, valueB)
+3
source

All Articles