Integer division

Dan Bishop danb_83 at yahoo.com
Fri Jun 8 00:08:06 EDT 2007


On Jun 7, 8:30 pm, Some Other Guy <bga... at microsoft.com> wrote:
> jm.sur... at no.spam.gmail.com wrote:
> > Hello all,
> >  I have two integers and I want to divide one by another, and want to
> > get an integer result which is the higher side whenever the result is
> > a fraction.
> >  3/2 => 1 # Usual behavior
> >  some_func(3, 2) => 2 # Wanted
>
> Are you trying to accomplish int((a/b) + 0.5), but cheaply?
>
> If so, consider that that is the same as (a/b) + (b/2b),
> which is (2a/2b) + (b/2b), which is (2a+b)/2b.
>
> Since this just involves doubling you can avoid multiplying altogether
> and just use this:
>
> def rounddiv(a,b):
>   return int((a+a+b)/(b+b))
>
> That's 3 integer adds and 1 integer divide.  The int() cast is just
> there is case somebody passes in floats for a or b; if you know you're
> only going to have integer arguments you don't need it.

The // operator was added to the language for a reason.  I'm surprised
at how few Pythonistas are using it six years later.




More information about the Python-list mailing list