Ttys
Ttys

Reputation: 93

how to sum different values of a function?

I need help on summation of different values of function. Here a piece of code

n = 4
a = np.arange(0.0,n+1,1)
def n(a):
    return 11.0+(a**2)/((2.1)**(2.0)*(1/4))

print n(a)

it works but I need n(0)+n(1)+n(2)+n(3)+n(4) as a single result

Upvotes: 2

Views: 97

Answers (2)

gboffi
gboffi

Reputation: 25023

You can sum the elements of the array like this (look especially at the last line)

N = 4
a = np.linspace(0, N, N+1)

def n(a):
    return 11.0+(a**2)/((2.1)**(2.0)*(1/4))

print(n(a))
print(n(a).sum())

It works because n(a) returns a ndarray object (a Numpy vector) and a ndarray has a number of interesting pre-defined methods, among them .sum() whose intent is, I hope so, clear enough.


Test

In [7]:     N = 4 
   ...:     a = np.linspace(0, N, N+1) 
   ...:      
   ...:     def n(a): 
   ...:         return 11.0+(a**2)/((2.1)**(2.0)*(1/4)) 
   ...:      
   ...:     print(n(a)) 
   ...:     print(n(a).sum()) 
   ...:                                                                                   
[11.         11.90702948 14.62811791 19.16326531 25.51247166]
82.21088435374149

Upvotes: 1

Zags
Zags

Reputation: 41210

Try the following:

sum(n(i) for i in range(5))

Upvotes: 1

Related Questions