-3

I am running this little loop on a Jupyter notebook

import time

def time_loop(reps):

    start = time.clock()
    count = 0
    for i in range(reps):
        count += 1
    return time.clock() - start

time_loop(10000^100)

No matter what I enter as an argument, I seem to always get an output around 0.003

0.0031050000000050204

What is going on?

One guess is that python understands that the result of the loop will simply be count = reps, and quits the loop?

But if I run this instead

import time
import numpy as np

def time_loop(reps):

    start = time.clock()
    count = 0
    for i in range(reps):
        count += np.sin(reps)
    return time.clock() - start

time_loop(10000^100)

It does take longer as I increase the argument, even though the result of the loop is still quite simply count = reps*sin(reps).

Andrea
  • 302
  • 2
  • 6
  • 12

1 Answers1

1

^ is xor and not exponentation:

>>> 10000^100
10100

That's a big number but not like with exponentation: **, that returns:

>>> 10000**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

That also takes a "while" to iterate over.

A good reference for the operators and their precedence is avaiable in the python documentation:

^ - Bitwise XOR

** - Exponentiation

Community
  • 1
  • 1
MSeifert
  • 145,886
  • 38
  • 333
  • 352