long int computations

Jerry Hill malaclypse2 at gmail.com
Mon May 3 11:41:31 EDT 2010


On Mon, May 3, 2010 at 11:17 AM, Victor Eijkhout <see at sig.for.address> wrote:
> I have two long ints, both too long to convert to float, but their ratio
> is something reasonable. How can I compute that? The obvious "(1.*x)/y"
> does not work.

You didn't say what version of python you were using, but this seems
to work for me in 2.6.4:

>>> long1 = 10**1000
>>> long2 = long1 * 2
>>> float(long1)

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    float(long1)
OverflowError: long int too large to convert to float

>>> long1/long2
0L

>>> from __future__ import division
>>> long1/long2
0.5

The "from __future__ import division" line gets python to return a
float as the result of dividing two integers (or longs), instead of
returning an integer.  If I recall correctly, this has been available
for quite a few python versions (since 2.2 maybe?), and has become the
default in python 3.

If you need to do integer division, you would use the // operator:

>>> long1 // long2
0L

Hope that helps.


-- 
Jerry



More information about the Python-list mailing list