Arbitrary precision integer arithmetic: ceiling?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Mar 8 20:48:21 EST 2008


On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote:

> On Mar 8, 6:26 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
>> Alasdair <amc... at gmail.com> writes:
>> > What is the best way of finding a ceiling of a quotient of arbitrary
>> > sized integers?
>>
>> ceiling(a/b) = (a+b-1)//b
> 
> I prefer:
> 
> ceiling(a/b) = -(-a)//b
> 
> which also works if a and b are something other than integers (e.g.
> rational numbers).


Unfortunately it doesn't give the right answer.

>>> a, b = 101.0, 10.0
>>> -(-a)//b  # should be 11.0
10.0
>>> a, b = -101.0, 10.0
>>> -(-a)//b  # should be -10.0
-11.0

Looks like you've confused ceiling() and floor().

(And the ease that these mistakes can happen is why such fundamental 
functions should be in the standard library, no matter how easy they are 
to implement.)


-- 
Steven



More information about the Python-list mailing list