The Mersenne Twister period used in the random module, (I said) 2 ** 19937 - 1. As a binary number, that is 19937 '1 in a row (if I'm not mistaken), Python converts it to decimal pretty quickly:
$ python -m timeit '2**19937' 10000000 loops, best of 3: 0.0271 usec per loop $ python -m timeit -s 'result = 0' 'result += 2**19937' 100000 loops, best of 3: 2.09 usec per loop
I assume the second version requires conversion?
And this is not just binary. It is also fast. (Instead of showing numbers, I show the length of the decimal number converted to a string):
>>> import math >>> N = 1000 >>> s = str((int(N*math.e))**(int(N*math.pi))) >>> len(s) 10787 >>> N = 5000 >>> s = str((int(N*math.e))**(int(N*math.pi))) >>> len(s) 64921
Timing:
python -m timeit -s 'import math' -s 'N=1000' = str((int(N*math.e))**(int(N*math.pi)))' 10 loops, best of 3: 51.2 msec per loop
Question: how is this done?
Am I just naive to be impressed? I find a look at the Python shell creating some 5,000 or so places in an instant, truly breathtaking.
Edit:
Additional timings offered by @dalke and @truppo
$ python -m timeit 'x=2' 'x**19937' 1000 loops, best of 3: 230 usec per loop $ python -m timeit 'x=2' 'int(x**19937)' 1000 loops, best of 3: 232 usec per loop $ python -m timeit 'x=2' 'str(x**19937)' 100 loops, best of 3: 16.6 msec per loop $ python -m timeit -s 'result = 0' 'x = 2' 'result += x**19937' 1000 loops, best of 3: 237 usec per loop $ python -m timeit -s 'result = 0' 'x = 2' 'result += x**19937' 'int(result)' 1000 loops, best of 3: 238 usec per loop $ python -m timeit -s 'result = 0' 'x = 2' 'result += x**19937' 'str(result)' 100 loops, best of 3: 16.6 msec per loop
So it seems to me that result = 0; result += 2**19937 result = 0; result += 2**19937 probably forces the conversion.
python largenumber computation
telliott99
source share