Home > Mobile >  Is there an efficient np.sum with exponent operator possible in Python?
Is there an efficient np.sum with exponent operator possible in Python?

Time:02-25

I have a quick question which I can't find asked anywhere (yet). Is there a quick and efficient way to perform an operation like this:

Sum with exponent

Where gamma is a constant. So to put it simply: take the sum of all gamma's raised to the power of i. I have fooled around a bit with np.sum and np.exp but this seems to be my best guess:

n = 4
gamma = 2
np.sum([gamma**i for i in range(n)])

Let me know what you've come up with :)

CodePudding user response:

You can generate all the powers with one numpy expression:

In [131]: n = 4
     ...: gamma = 2
     ...: np.sum([gamma**i for i in range(n)])
Out[131]: 15
In [132]: np.sum(gamma ** np.arange(n))
Out[132]: 15

CodePudding user response:

As @Mark explained, the best solution is rewriting the sum into the simple formula:

(gamma ** (n - 1))/(gamma - 1)

Thanks everyone!

  • Related