A use for integer quotients
Just van Rossum
just at letterror.com
Tue Jul 24 05:15:34 EDT 2001
Christian Tanzer wrote:
>
> Just van Rossum <just at letterror.com> wrote:
>
> > > As for the second line: do you really think
> > > int(float(bytes)/float(k)+.5) is signigicantly better for rounding?
> >
> > 1) only one of the / operands need to be a float to force a float
> > outcome, and 2) there is a round() builtin function. Now, if we
> > initialize k to a float, we can write it like so:
> >
> > int(round(bytes/k))
>
> My version of the Python Library Reference Manual (Release 2.1, 15
> April 2001) says:
>
> Conversion from floating point to (long or plain) integer may
> round or truncate as in C; see functions floor() and ceil() in the
> math module for well-defined conversions.
>
> That means that one should not use `int` to convert from float to
> integer. No using `int (math.floor (a/b))` is quite a mouthful but
> everybody caring about version compatibility will have to use such
> abominations for a long time. (For instance, my main customer will
> ship based products on 1.5.2 for several month to come, the shift to
> 2.x *may* happen with the next major release which is planned for
> the last quarter of the year).
Erm, I did round(a/b), after which a conversion with int() is perfectly
safe. But in general, it seems you're entirely correct.
Just
More information about the Python-list
mailing list