lundi 23 mars 2020

Numpy asserts -0.0 is not equal to 0.0

I have a named tuple with strings and floats. I'm using Numpy's testing methods across my application. I have a situation where my actual results are returned at -0.0 where my desired is 0.0. Although Python treats these objects as equal, my Numpy assertions are failing. I can't use almost_equal or approx_equal because of the mixed types within the namedtuple.

Does anyone have a workaround?

Here's a simple example.

>>> import numpy as np
>>> np.testing.assert_equal(-0.0, 0.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.8/site-packages/numpy/testing/_private/utils.py", line 420, in assert_equal
    raise AssertionError(msg)
AssertionError: 
Items are not equal:
 ACTUAL: -0.0
 DESIRED: 0.0
>>> -0.0 == 0.0
True

Why can't I use almost_equal or approx_equal?

>>> from collections import namedtuple
>>> point = namedtuple("Point", ["name", "x", "y"])
>>> p_1 = point("Jim", 0.0, -0.0)
>>> p_2 = point("Jim", 0.0, 0.0)
>>> np.testing.all_close(p_1, p_2)

Puke...

Aucun commentaire:

Enregistrer un commentaire