long int computations
Peter Otten
__peter__ at web.de
Mon May 3 12:39:33 EDT 2010
Peter Pearson wrote:
> On Mon, 03 May 2010 17:30:03 +0200, Peter Otten <__peter__ at web.de> wrote:
>> Victor Eijkhout 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.
>>
>>>>> import fractions
>>>>> x = 12345 * 10**1000
>>>>> y = 765 * 10**1000
>>>>> float(x)
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> OverflowError: long int too large to convert to float
>>>>> fractions.Fraction(x, y)
>> Fraction(823, 51)
>>>>> float(_)
>> 16.137254901960784
>
> Does this still work if y = 765 * 10**1000 + 1 ? It looks
> as if it might rely on x and y having a large common divisor.
You mean something like this?
>>> import fractions
>>> x = 765 * 10**1000
>>> fractions.gcd(x, x+1)
1L
>>> float(fractions.Fraction(x, x+1))
1.0
But my D'oh!* moment really was seeing Jerry Hill doing it with
>>> from __future__ import division
>>> x/(x+1)
1.0
Peter
(*) I'm having a lot of these lately. Looks like I need a new brain.
More information about the Python-list
mailing list