(-1)**1000

Peter Otten __peter__ at web.de
Wed Oct 22 06:29:45 EDT 2014


ast wrote:

> 
> "Chris Angelico" <rosuav at gmail.com> a écrit dans le message de
> news:mailman.15058.1413968065.18130.python-list at python.org...
>> On Wed, Oct 22, 2014 at 7:27 PM, ast <nomail at invalid.com> wrote:
>>> If i am writing (-1)**1000 on a python program, will the
>>> interpreter do (-1)*(-1)*...*(-1) or something clever ?
>>>
>>> In fact i have (-1)**N with N an integer potentially big.
>>
>> Exponentiation is far more efficient than the naive implementation of
>> iterated multiplication.
> 
> In the very particular case of (-1)**N,  I belive that Python check
> the odd or even parity of N and provides the result accordingly.
> 
> I tried:
>>>> (-1)**1000000000000000000000000000000000
> 1
>>>> (-1)**1000000000000000000000000000000001
> -1
> 
> and it is instantaneous

Not instantaneous once you defeat the peephole optimizer by introducing a 
variable:

$ python3 -m timeit '(-1)**10000000000000000000000000000000001'
10000000 loops, best of 3: 0.0356 usec per loop
$ python3 -m timeit -s'a = 10000000000000000000000000000000001' '(-1)**a'
100000 loops, best of 3: 3.23 usec per loop

When you increase the exponent you might discern a pattern:

$ python3 -m timeit -s 'a = 10**10' '(-1)**a'
1000000 loops, best of 3: 1.42 usec per loop
$ python3 -m timeit -s 'a = 10**100' '(-1)**a'
100000 loops, best of 3: 11.6 usec per loop
$ python3 -m timeit -s 'a = 10**1000' '(-1)**a'
10000 loops, best of 3: 101 usec per loop
$ python3 -m timeit -s 'a = 10**10000' '(-1)**a'
1000 loops, best of 3: 992 usec per loop

That looks like log(a) while a parity check takes constant time:

$ python3 -m timeit -s 'a = 10**10' 'a & 1'
10000000 loops, best of 3: 0.124 usec per loop
$ python3 -m timeit -s 'a = 10**100' 'a & 1'
10000000 loops, best of 3: 0.124 usec per loop
$ python3 -m timeit -s 'a = 10**1000' 'a & 1'
10000000 loops, best of 3: 0.122 usec per loop





More information about the Python-list mailing list