Calculate Big Number
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Jan 8 00:50:58 EST 2013
On Tue, 08 Jan 2013 02:44:04 +0200, Nac Temha wrote:
> Hello,
> How to *quickly* calculate large numbers. For example
>>>> (10**25) * (2**50)
> 11258999068426240000000000000000000000000L
Timing how long that takes is trickier than it seems, because modern
versions of Python include a keyhole optimizer that will optimize some,
or all, of that calculation to constant(s). In Python 2.7:
py> import dis
py> code = compile("(10**25) * (2**50)", "", "single")
py> dis.dis(code)
1 0 LOAD_CONST 5 (10000000000000000000000000L)
3 LOAD_CONST 6 (1125899906842624L)
6 BINARY_MULTIPLY
7 PRINT_EXPR
8 LOAD_CONST 4 (None)
11 RETURN_VALUE
So, here's the best of five attempts to calculate the above in full, with
no optimizations, one hundred thousand times:
py> from timeit import Timer
py> t1 = Timer("(a**b)*(c**d)", setup="a,b,c,d = 10, 25, 2, 50")
py> min(t1.repeat(repeat=5, number=100000))
0.5256571769714355
So that's about 5 microseconds on my (slow) computer.
You can find the source code here:
http://hg.python.org/cpython/file/944e86223d1f/Objects/longobject.c
--
Steven
More information about the Python-list
mailing list