473,804 Members | 3,716 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arbitrary precision integer arithmetic: ceiling?

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?

Thanks,
Alasdair
Mar 8 '08 #1
15 3901
Alasdair <am****@gmail.c omwrites:
What is the best way of finding a ceiling of a quotient of arbitrary sized
integers?
ceiling(a/b) = (a+b-1)//b
Mar 8 '08 #2
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(100000000 000000000000000 003, 10)
Out[16]: 100000000000000 00000000001L

--
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

Mar 8 '08 #3
On Mar 8, 6:26*pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
Alasdair <amc...@gmail.c omwrites:
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).

Mark
Mar 9 '08 #4
On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote:
On Mar 8, 6:26Â*pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
>Alasdair <amc...@gmail.c omwrites:
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
Mar 9 '08 #5
On Mar 8, 8:48*pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com .auwrote:
On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote:
I prefer:
ceiling(a/b) = -(-a)//b

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().
Whoops, you're right. No, I didn't confuse ceiling and floor;
I misplaced the parentheses. I meant to type:

ceiling(a/b) = -(-a//b)

Mark
Mar 9 '08 #6
On Sat, 08 Mar 2008 15:26:35 -0800, Paul Rubin wrote:
Alasdair <am****@gmail.c omwrites:
>What is the best way of finding a ceiling of a quotient of arbitrary
sized integers?

ceiling(a/b) = (a+b-1)//b

Unfortunately that doesn't work reliably.
>>a, b = 900719925474100 0.0, -3.0
a/b
-300239975158033 3.5
>>(a+b-1)//b # should be -300239975158033 3
-300239975158033 2.0

I make no claim that this is the most efficient way to do it, but this
should work:
def splitfloat(f):
"""Return the integer and fraction part of a float."""
fp = abs(f) % 1.0
ip = abs(f) - fp
if f < 0:
ip, fp = -ip, -fp
return (ip, fp)

def ceil(f):
ip, fp = splitfloat(f)
if fp == 0:
return ip
elif f < 0:
return ip
else:
return ip + 1

>>a, b = 900719925474100 0.0, -3.0
ceil(a/b)
-300239975158033 3.0
>>a, b = 900719925474100 0.0, 3.0
ceil(a/b)
300239975158033 4.0

It even works for infinities, if supported by your platform:
>>ceil(1.0/inf)
0.0

(Disclaimer: if you consider that 1.0/inf is a tiny bit more than zero,
and therefore you want ceil(1.0/inf) to give 1.0, then you will disagree
with me.)

--
Steven
Mar 9 '08 #7

"Steven D'Aprano" <st***@REMOVE-THIS-cybersource.com .auwrote in message
news:13******** *****@corp.supe rnews.com...
| On Sat, 08 Mar 2008 17:09:11 -0800, Mark Dickinson wrote:
|
| On Mar 8, 6:26 pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
| >Alasdair <amc...@gmail.c omwrites:
| 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

Obvious typo: -(-a)//b == a//b

This should be -(-a//b) == -((-a)//b)

| Unfortunately it doesn't give the right answer.
| 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.)

I'll let Paul say whether is was a typo, due to answering too quickly, or a
logic error, but I suspect the former. *Any* expression can be mistyped.

tjr

Mar 9 '08 #8
On Sun, 09 Mar 2008 01:48:21 +0000, Steven D'Aprano wrote:
(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.)
Which, of course, they are.

math.ceil() and math.floor()

I knew that. *cough*

--
Steven
Mar 9 '08 #9
On Sun, 09 Mar 2008 10:11:53 +1100, 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?
def quot_ceil(a, b):
"""Returns the integer ceiling of the quotient of longints."""
q, r = divmod(a, b)
if r: return q+1
else: return q

--
Steven
Mar 9 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1703
by: Thinkit | last post by:
Are there any packages for arbitrary precision binary floats? Something along the lines of Gnu Multi Precision. I saw quite a few rationals classes, but not this. Just looking to be able to use any mantissa or exponent I want. Of course it would be software based arithmetic.
4
7854
by: Roger Leigh | last post by:
Hello, I'm writing a fixed-precision floating point class, based on the ideas in the example fixed_pt class in the "Practical C++ Programming" book by Steve Oualline (O' Reilly). This uses a long int to store the value, and the precision (number of decimal points) is variable (it's a templated class): template <size_t _decimal_places = 4> class FixedFloat {
2
1474
by: cpptutor2000 | last post by:
Could some C++ guru please help me? I am using a BigInteger class which is really a wrapper around a C source file(mpi.c) that does arbitrary precision arithmetic operations. When I compile the C file using gcc -g -o mpi mpi.c rng.c -lm there are NO compilation or linking errors. However, when I try to compile the C++ wrapper class using g++ -g -o bigint bigint.C mpi.c rng.c -lm, I get strange linkage problems that all the functions in...
37
6377
by: Protoman | last post by:
Hi!!! Protoman here, I need to write an infinite precision number class b/c I want to compute pi. Give me some sample code. Also, when I run my program and it computes pi, will my computer freeze b/c it's infinite precision? Thanks for the help!
3
23761
by: Madan | last post by:
Hi all, I had problem regarding float/double arithmetic only with + and - operations, which gives inaccurate precisions. I would like to know how the arithmetic operations are internally handled by C# or they are hardware (processor) dependent. Basic addition operation errors, for ex: 3.6 - 2.4 = 1.19999999999 or 1.20000000003 There are the erroneous values I'm getting. I'm using C#.Net v1.1 Please reply me how these operations are...
0
955
by: Jeremy Watts | last post by:
Hi, Does VB.net have an 'arbitrary length' arithmetic feature? Meaning can it handle very large real/integer number arithmetic symbolically like some other languages can? PHP for instance has the 'BC arithmetic' function that allows arithmetic involving very large numbers. Its just that I am considering switching languages from PHP to maybe C++ or VB.net
2
3033
by: rupert | last post by:
i've got the following code: #include <iostream> #include <string> #include <vector> #include <iomanip> using namespace std; int main(double argc, char* argv) { double r = 0.01;
11
10014
by: ChrisM | last post by:
Hi Guys, I'm looking for a function that will return the lowest integer that is greater than or equal to a decimal number. eg. 3.1(decimal) returns 4(integer) 3.9(decimal) returns 4(integer) 4.0(decimal) returns 4(integer)
2
1899
by: Rob Clewley | last post by:
Dear Pythonistas, How many times have we seen posts recently along the lines of "why is it that 0.1 appears as 0.10000000000000001 in python?" that lead to posters being sent to the definition of the IEEE 754 standard and the decimal.py module? I am teaching an introductory numerical analysis class this fall, and I realized that the best way to teach this stuff is to be able to play with the representations directly, in particular to be...
0
9707
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9585
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10586
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10323
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7622
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5658
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3823
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2997
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.