A use for integer quotients

Steve Horne sh at ttsoftware.co.uk
Mon Jul 23 14:15:33 EDT 2001


On Mon, 23 Jul 2001 08:54:08 -0700, Erik Max Francis <max at alcyone.com>
wrote:

>Just van Rossum wrote:
>
>> Do you really want 2047 bytes to be shown as 1 kbyte? Integer division
>> is a lousy tool in this particular example...
>
>Just add 512 to it first.

The oldest trick in the book - it scares me that something so basic is
considered a problem. Rounding can be done according to a number of
conventions - magically turning integers into floats changes a task
that is trivially done exactly into one that involves approximations
and conditionals, and which can easily create subtle special-case
bugs.

Consider - you want to round to two decimal places. So you multiply by
100.0, round to integer, then divide by 100.0.

That division will not give an exact result, so the result cannot be
considered rounded to two decimal places without a lot of careful
provisos.

Fixed point arithmetic emulated by using integers with a scale factor,
though, works very nicely. Better still when there's a language
feature to do this automatically, but if we added fixed point types to
Python we'd need *another* division operator - four so far including
the rational one ;-)

-- 
Steve Horne
Home : steve at lurking.demon.co.uk
Work : sh at ttsoftware.co.uk



More information about the Python-list mailing list