"Alan Gauld" <alan.ga...@btinternet.com> wrote in message news:ht6v97$63...@dough.gmane.org...

"Neven Gorsic" <neven.gor...@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


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to