Overflow error

Scott David Daniels Scott.Daniels at Acm.Org
Wed Jul 28 18:58:42 EDT 2004


Michael Hudson wrote:

> janeaustine50 at hotmail.com (Jane Austine) writes:
> 
> 
>>>>>from math import e
>>>>>e**709
>>
>>8.218407461554662e+307
>>
>>>>>e**710
>>
>>Traceback (most recent call last):
>>  File "<pyshell#15>", line 1, in -toplevel-
>>    e**710
>>OverflowError: (34, 'Result too large')
>>
>>What should I do to calculate e**710?
> 
> 
> Well, it's too big for your platform's C double, so you need a
> different representation.  I don't know if there are big float
> packages out there that handle such things (likely, though) or if
> there are Python interfaces to the same (less likely).  Or you could
> store the logarithms of the numbers you are interested in.  Why do you
> need such huge nubmers?
> 
> Cheers,
> mwh
> 
Using a little bit of magic:

First get a good approximation of e:
Using my bits package, I can do:

     import bits, math
     scaling = bits.lsb(math.e)
     characteristic = bits.extract(math.e, scaling, 10)
     # This has the same effect as:
     # scaling, characteristic = -51, 6121026514868073L
     # Now e = characteristic * 2.**scaling
     result_scaling = scaling * 710
     result_characteristic = characteristic ** 710
     intpart = result_characteristic >> -result_scaling
     # and you'll have to grab as much fractpart as you want.

Similarly, for decimal, type in enough digits (for your taste) of e
from some reference book, and omit the decimal point.
Then track the exponent in base ten, and you can obtain similar results:

     scaling, characteristic = -5, 271828
     result_scaling = scaling * 710
     result_characteristic = characteristic ** 710
     intpart = result_characteristic // 10 ** -result_scaling


So, you needn't use floating point if you are willing to type in
constants.  Both of these give a number which is 223. * 10 ** 50 to
three digits, and they differ in the fourth digit (4 or 3 if you round).
The binary-based version (the first above) produces:
     2233994766....
While the decimal-based version produces:
     2232928102....
This is certainly due to using so few decimal places for e in the
decimal version.
In Knuth's Art of Computer Programming (at least volume 3, which I
happen to have at hand) Appendix A, you can get 41 decimal digits for e,
or 45 octal digits if you prefer to work with binary.  I believe
(without checking) that each of the volumes contains this appendix.
The big advantage of using decimal is (a) more readily available tables
of constants come in decimal than in binary, and (b) if you _do_ want
to print some of the fractpart, it is easier just to change the division
to include the extra digits, while for the binary versions you'll have
to multiply by 10**digits before the division.

-- 
-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list