Newbie question about function return values

Erik Max Francis max at alcyone.com
Fri Mar 14 20:46:26 EST 2003


Chad Netzer wrote:

> > Try this:
> >
> > def round_to_higher_mult_of_512(x):
> >    return ((x + 511L) // 512L) * x
> >    # 'L' just in case rounded-up file size >= 2GB
> 
> ???
> 
> >>> round_to_higher_mult_of_512(511)
> 511L
> >>> round_to_higher_mult_of_512(513)
> 1026L

I suspect that's just a thinko; he probably meant to write:

	return ((x + 511) // 512) * 512

i.e., if x is the number and M is the multiple of which you want it
rounded to, then the expression desired is

	((x + (M - 1)) // M) * M

This is a pretty standard idiom, I've seen it time and again.

> I'll suggest this instead:
> 
> # Will automatically promote to long int in python 2.2.x
> def round_to_higher_mult_of_512(x):
>     return (x//512 + 1) * 512

This doesn't work for the case when x _is_ a multiple of 512:

>>> def g(x):
...  return (x/512 + 1) * 512
... 
>>> g(512)
1024

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The more violent the love, the more violent the anger.
\__/ _Burmese Proverbs_ (tr. Hla Pe)
    Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
 A personal guide to Aliens vs. Predator 2.




More information about the Python-list mailing list