[Tutor] Python 2.5.4 - error in rounding

Mark Tolonen metolone+gmane at gmail.com
Sat May 22 04:16:24 CEST 2010


"Alan Gauld" <alan.gauld at btinternet.com> wrote in message 
news:ht6v97$632$1 at dough.gmane.org...
>
> "Neven Gorsic" <neven.gorsic at gmail.com> wrote
>
>> I run into Python error in rounding and not know how to predict when it 
>> will
>> occur in order to prevent wrong result.
>
> It depends how you define wrong. When I was at scvhool the rules f
> or rounding decimals said that if it ended in 5 you rounded to the
> nearest even digit.
> So 0.45 -> 0.4 and 0.55 ->0.6
>
> But you seem to assume a 5 always rounds up...
>
>> What can I do to assure accurate result?
>
> Just to be picky, Python is being accurate, but it is
> accurately reflecting the binary value... But I think
> you knew that! :-)
>
>>
>>>>> "%.2f" % 0.465
>> '0.47'                                   correct
>>>>> "%.2f" % 0.475
>> '0.47'                                   not correct
>>>>> "%.2f" % 0.485
>> '0.48'                                   not correct
>
> The good news is that python's round() function seems
> to have had the same teacher as you :-)
> So
>
>>>>> "%.2f" % round(0.475,2)
>> '0.48'
>>>>> "%.2f" % round(0.485, 2)
>> '0.49'

Only coincidentally!

>>> .475
0.47499999999999998 # %.2f will round down to 0.47
>>> .485
0.48499999999999999  # %.2f will round down to 0.48
>>> round(.475,2)
0.47999999999999998 # %.2f will round up to 0.48
>>> round(.485,2)
0.48999999999999999 # %.2f will round up to 0.49

-Mark




More information about the Tutor mailing list