[Tutor] The '45' bug in round()
Kent Johnson
kent37 at tds.net
Mon Mar 19 12:24:39 CET 2007
Dick Moores wrote:
> Kent, I did understand the points you made in that earlier thread.
> However, I'm unhappy with
>
> >>> print round(0.19945,4)
> 0.1994
>
> Am I the only one unhappy with this kind of rounding?
IMO you are chasing a non-problem. In real-world use, you would probably
not type in a number and then immediately round it. You would round the
result of some calculation that itself starts with inexact values and
then introduces more error. To take the result of this calculation and
second-guess it seems silly to me.
> My function, round2() restores me to happiness. :)
Well I should leave well enough alone then :-)
> >>> print round2(0.19945,4)
> 0.1995
>
> Is there something wrong with it?
If you want exact decimal representations you may be better off using
the decimal module than trying to patch binary floating point. Though
decimal has its own representation error...
Kent
More information about the Tutor
mailing list