Thursday, 19 September 2013

Rounding issues when converting between arrays and tuples

Rounding issues when converting between arrays and tuples

I have a nested list of 2-element lists (lat/lon coordinates)
xlist = [[-75.555476, 42.121701],
[-75.552684, 42.121725],
[-75.55268, 42.122023],
[-75.55250199999999, 42.125071999999996],
[-75.552611, 42.131277] ... ]
that I want to convert into a set. Before I do the conversion, however, I
really want to round these values down to a lower precision so I can
perform set operations on other similar lists and look for points common
to both lists.
I can round with numpy,
x = np.round( xlist, decimals = 4 )
array([[-75.5555, 42.1217],
[-75.5527, 42.1217],
[-75.5527, 42.122 ],
...,
[-75.5552, 42.1086],
[-75.5553, 42.1152],
[-75.5555, 42.1217]])
but then the resulting object is a numpy array which I can't convert to a set
s = set( x )
TypeError: unhashable type: 'numpy.ndarray'
I tried converting the array back into a tuple of tuples
t = ( tuple( row ) for row in x )
but this does nasty things to the precision in the conversion
t.next()
(-75.555499999999995, 42.121699999999997)
I've also tried doing this in a single step, and had no luck
map( tuple, np.round( x, decimals =5 ) )
[(-75.555480000000003, 42.121699999999997),
(-75.552679999999995, 42.121720000000003),
(-75.552679999999995, 42.122019999999999),
(-75.552499999999995, 42.125070000000001)]
Is there something I'm missing about converting between tuples and arrays?
How can I get from a list to a set that has its items rounded to lower
precision?

No comments:

Post a Comment