(-1)**1000

Chris Angelico rosuav at gmail.com
Wed Oct 22 04:54:16 EDT 2014


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. Any modern programming language on any modern
CPU architecture should be able to handle this kind of thing. But even
the naive approach is likely to be fast enough.

>>> x=1
>>> for i in range(1000000): x*=-1

I had to go as far as a million iterations before this, implemented
purely in Python with absolutely no optimization, demonstrated a
visible pause (of about a quarter second) on my not-exactly-new
Windows laptop. My Linux desktop, with a rather hotter CPU, has no
trouble with a million, so I'd have to go higher to get a pause out of
it.

And actually, about half of that time is spent in the loop - replacing
the assignment with "pass" still leaves half the iteration time.

Poor performance is a crime. Python is innocent until proven guilty.
And the burden of proof is seldom met.

ChrisA



More information about the Python-list mailing list