Have noticed some rather peculiar behaviour in numpy regarding differentiating -0.0 from 0.0. Here are some examples:
#normal python doesn't distinguish between 0 and -0:
>>> -0
0
>>> -0==0
True
#numpy also sometimes changes -0 to 0:
>>> import numpy as np
>>> np.array([-0])
array([0])
#HERE IS THE SURPRISE - numpy does seem to have separate 0 and -0:
>>> np.round(0.1)
0.0
>>> np.round(-0.1)
-0.0
#yet numpy is of course aware that -0 and 0 are equal:
>>> np.round(-0.1) == np.round(0.1)
True
#python round() function doesn't behave like this:
>>> round(0.1)
0
>>> round(-0.1)
0
Background - why do I care about this? Because I have a list of numpy arrays and I want to remove arrays which are equal to another array in the list to 2d.p.. To do this, I changed the list of arrays to a dict of arrays, where the key of each item is the array rounded to 2d.p. Now an array can't be used as a dict key, so I used .tobytes() after rounding it, and the byte representation of the rounded array is the item's key. The item's value is the unrounded array, as I want to keep the precision.
Imagine my surprise when I noticed this didn't get rid of identical arrays, simply because one had a -0 and the other a 0...
>>> np.round(0.1).tobytes() #ends with x00
b'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> np.round(-0.1).tobytes() #ends with x80
b'\x00\x00\x00\x00\x00\x00\x00\x80'
>>> np.round(0.1).tobytes() == np.round(-0.1).tobytes() #well obviously this will be False
False
Why does numpy store -0 and 0 differently, and why sometimes and not always? Are there other examples of this behaviour - the above is what I've come up with so far. Why is numpy different to python in this? Are there any examples when python also has separate 0 and -0? How can I get my code to recognise that -0 and 0 in one position in the array are identical? If you have -0.0, then adding 0 changes it to 0, but subtracting 0 leaves it at -0.0. Why is this?