How to handle rounding to negative zero in Python docstring tests
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence
--
Chapters
00:00 Question
02:20 Accepted answer (Score 2)
02:53 Answer 2 (Score 0)
03:26 Thank you
--
Full question
https://stackoverflow.com/questions/6628...
Question links:
[How to have negative zero always formatted as positive zero in a python string?]: https://stackoverflow.com/questions/1101...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #numpy #docstring #doctest
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence
--
Chapters
00:00 Question
02:20 Accepted answer (Score 2)
02:53 Answer 2 (Score 0)
03:26 Thank you
--
Full question
https://stackoverflow.com/questions/6628...
Question links:
[How to have negative zero always formatted as positive zero in a python string?]: https://stackoverflow.com/questions/1101...
--
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. ]]