Arbitrary precision integer arithmetic: ceiling?
Robert Kern
robert.kern at gmail.com
Sat Mar 8 18:31:55 EST 2008
Alasdair wrote:
> I need to apply the ceiling function to arbitrary sized (long) integers.
> However, division automatically returns the type of its operands, so that,
> for example: math.ceil(7/4) returns 1. I can use float, as in:
> math.ceil(7/float(4)), except that for very large integers float causes an
> unacceptable loss of precision.
>
> What is the best way of finding a ceiling of a quotient of arbitrary sized
> integers?
Use divmod() to get the quotient and the remainder at the same time. Add 1 to
the quotient if and only the remainder is greater than 0.
In [11]: def qceil(x, y):
....: """ Find the ceiling of a quotient x/y.
....:
....: This is especially useful for very large Python long integers.
....: """
....: q, r = divmod(x, y)
....: if r > 0:
....: q += 1
....: return q
....:
In [13]: qceil(7, 4)
Out[13]: 2
In [14]: qceil(8, 4)
Out[14]: 2
In [15]: qceil(9, 4)
Out[15]: 3
In [16]: qceil(100000000000000000000000003, 10)
Out[16]: 10000000000000000000000001L
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list