Why does the App Engine show different results of rounding the float compared to my local machine?

If you put the following in Shell for applications , you will get '50.49'. This result is consistent both at runtime 2.5 and 2.7.

 >> a = '%0.2f' % (round(float(u'50.485'), 2),)
 >> a
'50.49'

However, if I put the same in my local MacBook Pro, working with python 2.7.1, I get '50.48'.

 >> a = '%0.2f' % (round(float(u'50.485'), 2),)
 >> a
'50.48'

Why is this different and how can I get consistency between my local machine and App Engine servers?

+5
source share
3 answers

Apparently, the Google App Engine uses type “float” type C (IEEE 754 single-point precision), while local Python instead uses “double” (IEEE 754 double-precision).

, CPython configure 'float' 'double', .

+4

, Python.

:
http://docs.python.org/2/tutorial/floatingpoint.html

. , 2.675 ,

>>>
>>> round(2.675, 2)
2.67

round() , , . 2.675 2,67 2,68, , ( ) 2.68. , 2.675 , ,

2.67499999999999982236431605997495353221893310546875

2,67, 2,68, .

, , , . , "" , Python

>>>
>>> from decimal import Decimal
>>> Decimal(2.675)
Decimal('2.67499999999999982236431605997495353221893310546875')

, Python (http://www.lahey.com/float.htm), FORTRAN, , IEEE 754:

. IEEE , - .. , FORTRAN.

, , ( cdecimal, http://pypi.python.org/pypi/cdecimal/2.3, ).

+2

The other answers are correct, so I won’t say anything about the behavior of the function round, but if you want consistent results, you can skip roundas you use the string format ( '%0.2f'), as you showed in your example.

>> a = '%0.2f' % (float(u'50.485'))
>> a
'50.48'
0
source

All Articles