The Python Oracle

How to handle rounding to negative zero in Python docstring tests

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ominous Technology Looping

--

Chapters
00:00 How To Handle Rounding To Negative Zero In Python Docstring Tests
01:46 Accepted Answer Score 2
02:09 Answer 2 Score 0
02:33 Thank you

--

Full question
https://stackoverflow.com/questions/6628...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy #docstring #doctest

#avk47



ACCEPTED ANSWER

Score 2


You can print the rounded array plus 0.0 to eliminate the -0:

A = np.array([[1, 0, 1], [0, 1, 0], [1, 0, 1]])
Q = orth(A)
Q[0,1] = -1e-16   # simulate a small floating point deviation

print(np.array2string(Q.round(8)+0.0, precision=8, suppress_small=True))
#[[-0.70710678  0.        ]
# [ 0.          1.        ]
# [-0.70710678  0.        ]]

So your doc string should be:

>>> Q = orth(A)
>>> print(np.array2string(Q.round(8)+0.0, precision=8, suppress_small=True)) # guarantee non-negative zeros
[[-0.70710678  0.        ]
 [ 0.          1.        ]
 [-0.70710678  0.        ]]



ANSWER 2

Score 0


Here's another alternative I came up with, although I think I like rounding the array to the given precision better. In this method, you shift the whole array by some amount that is bigger than the round-off error, but smaller than the precision comparison. That way the small numbers will still always be slightly positive.

    >>> Q = orth(A)
    >>> print(np.array2string(Q + np.full(Q.shape, 1e-14), precision=8, suppress_small=True))
    [[-0.70710678  0.        ]
     [ 0.          1.        ]
     [-0.70710678  0.        ]]