[Tutor] Summing arrays
Peter Otten
__peter__ at web.de
Thu Mar 16 05:33:05 EDT 2017
Aaliyah Ebrahim wrote:
> Hi guys! I hope you can assist me with understanding and fixing my error
> below. Thanks for this amazing forum :)
>
>
> def sum2(N):
>
> b = np.arange(1,N+1,1)
> mylist = [ ]
> for i in b:
>
>
> terms = 2*(1+3**(i-1))
> a = mylist.append[terms]
The immediate problem is that append is a method, the line above should be
mylist.append(terms)
As the append() method always returns None the assignment a = ...
does not do anything useful and should be avoided.
> return np.sum(mylist)
>
> print(sum2(N=50))
However, with the fix above you will still run into overflow errors with
your code. I suggest that you use Python's integer arithmetic and forget
about numpy for now:
$ cat tmp1.py
import numpy as np
def sum2(N):
b = np.arange(1,N+1,1)
mylist = []
for i in b:
terms = 2*(1+3**(i-1))
mylist.append(terms)
return np.sum(mylist)
def sum2a(N):
mylist = []
for i in range(1, N+1):
mylist.append(2*(1+3**(i-1)))
return sum(mylist)
print("N=5:", sum2(5), sum2a(5))
print("N=50:", sum2(50), sum2a(50))
$ python3 tmp1.py
N=5: 252 252
tmp1.py:7: RuntimeWarning: overflow encountered in long_scalars
terms = 2*(1+3**(i-1))
N=50: 6048575297968530476 717897987691852588770348
Both the numpy and the non-numpy version can be written more concisely (and
for the numpy version the rewritten version is more efficient, too):
$ cat tmp2.py
import numpy as np
def sum2(N):
b = np.arange(1, N+1, 1, dtype=float)
a = 2*(1+3**(b-1))
return a.sum()
def sum2a(N):
return sum(2*(1+3**(i-1)) for i in range(1, N+1))
print("N=5:", sum2(5), sum2a(5))
print("N=50:", sum2(50), sum2a(50))
$ python3 tmp2.py
N=5: 252.0 252
N=50: 7.17897987692e+23 717897987691852588770348
(Specifying dtype=float forces floating point arithmetic which is inexact)
More information about the Tutor
mailing list