Python simplejson coordinates issue

156 views Asked by At

The issue is that in my laptop i have the python 2.7.5 with some version of Simplejson and on my Debian 6 Server I have Python 2.6.6 with some simplejson version .. but whats happening on the debian server is that simplejson is adding extra precision to the coordinates value --

>>> import simplejson as json
>>> streamer_data = json.loads('{"text": "test","geo": {"type": "Point","coordinates":  [52.68908263, -8.50845340]},"coordinates": {"type": "Point","coordinates": [-8.50845340, 52.68908263]}}');

>>> print streamer_data
{u'text': test', u'geo': {u'type': u'Point', u'coordinates': [52.689082630000001, -8.5084534000000005]}, u'id': 420024061457346560L, u'coordinates': {u'type': u'Point', u'coordinates': [-8.5084534000000005, 52.689082630000001]}}

On my laptop this gives the correct result with proper precision to coordinates values --

>>> print streamer_data
{'text': 'test', 'geo': {'type': 'Point', 'coordinates': [52.68908263, -8.5084534]}, 'coordinates': {'type': 'Point', 'coordinates': [-8.5084534, 52.68908263]}}

Is this the Simplejson versioning problem or something else. Also note that i tried to figure out the version of simplejson on debian server but no success.

2

There are 2 answers

4
Ned Deily On BEST ANSWER

This difference between Python 2.6 and 2.7 has nothing to do with simplejson. In 2.7 there are changes to the algorithms used to produce the string representation and rounding of floating point numbers.

$ python2.6 -c "print([52.68908263, -8.50845340])"
[52.689082630000001, -8.5084534000000005]
$ python2.7 -c "print([52.68908263, -8.50845340])"
[52.68908263, -8.5084534]
0
Robert Siemer On

@Ned’s answer is correct, but I would like to add:

Your issue is only a visual one, both representations are exactly the same on a “normal” computer. Both are also not exactly of what the computer (can) store:

>>> a = 52.68908263
>>> b = 52.689082630000001
>>> '{0:.30} = {1:.30}: {2}'.format(a, b, a==b)
Python 2.6:
'52.6890826300000014725810615346 = 52.6890826300000014725810615346: True'
Python 2.7:
'52.6890826300000014725810615346 = 52.6890826300000014725810615346: True'

As visible now: no difference at all between those numbers. Python2.7 prints shorter representation of numbers, when it can make sure they round back to the same internal value. Python2.7 can do this only on some systems (with some compilers) (check sys.float_repr_style, it is “short” or “legacy”).