[Python-Dev] Rounding float to int directly (Re: struct module and coercing floats to integers)
M.-A. Lemburg
mal at egenix.com
Wed Aug 2 14:28:12 CEST 2006
Greg Ewing wrote:
> M.-A. Lemburg wrote:
>
>> You often have a need for controlled rounding when doing
>> financial calculations
>
> You should NOT be using binary floats for money
> in the first place.
Believe me: you have to if you want to do more
advanced calculus related to pricing and risk
analysis of derivatives.
>> or in situations where you want to
>> compare two floats with a given accuracy,
>
> Pseudo-rounding to decimal places is not
> the right way to do that. The right way is
> to compare the difference to a tolerance.
This is not the same: if you round both value
and then compare, you test a different interval
than by taking the difference and applying
a tolerance value comparison:
>>> x = 1.12
>>> y = 1.124999
>>> round(x,2) == round(y,2)
True
>>> abs(x-y) < 1e-2
True
yet:
>>> y = 1.1275
>>> round(x,2) == round(y,2)
False
>>> abs(x-y) < 1e-2
True
>> e.g. to work
>> around rounding problems ;-)
>
> As Tim Peters has pointed out many times,
> you can't fix binary/decimal representation
> problems by rounding. There are always cases
> that give a different result than you would
> want.
Right, but in most real-world cases it works :-)
>> Hmm, looks like a YAGNI to me,
>
> In all my programming so far I've found
> numerous uses for round-to-int, and exactly
> zero uses for round-binary-float-to-decimal-
> places. So from my point of view, the YAGNI
> applies to the *current* behavour of round()!
Most typical uses of round() don't use the
optional argument, true, but I still fail
to see what returning an integer instead of
a float would buy you.
--
Marc-Andre Lemburg
eGenix.com
Professional Python Services directly from the Source (#1, Aug 02 2006)
>>> Python/Zope Consulting and Support ... http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/
________________________________________________________________________
::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ::::
More information about the Python-Dev
mailing list