Pythmathician
Pythmathician

Reputation: 13

numpy array sum function

Let's say I have two one dimensional arrays, a and b, of length say n+1 and m+1.

I want c to be the an array of the same length as b, with elements equal to the sine of the sum of all a elements to the power b. Written in pseudo code below.

c = sum(sine(a[0:n] ** b[0])), sum(sine(a[0:n] ** b[1])),
  ... sum(sine(a[0:n] ** b[m])))

Is there a way I can accomplish this without using loops?

(Somewhat inexperienced in programming, hope my question makes sense.)

a function something ala this:

def function(a, b):
    c = np.sum(np.sin(a ** b))
    return c

Upvotes: 1

Views: 1172

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

If you want to sum the sines, you can first construct an m×n-matrix by using:

a.reshape(-1,1) ** b

Next we can calculate the sin of all these powers with np.sin(..):

np.sin(a.reshape(-1,1) ** b)

If we now want to sum over these sins, we can use np.sum(..) over the first axis:

np.sum(np.sin(a.reshape(-1,1) ** b),axis=0)

If a = [0,1,...,9] and b = [0,1] we obtain:

>>> a = np.arange(10)
>>> b = np.arange(2)
>>> np.sum(np.sin(a.reshape(-1,1) ** b),axis=0)
array([ 8.41470985,  1.95520948])

Since sin(0**0)+sin(1**0)+sin(2**0)+...+sin(9**0) = 10*sin(1) = 10*0.8414709848078965, the first value is correct. For the second one, this is equal to sin(0**1)+sin(1**1)+sin(2**1)+...+sin(9**1) = sin(0)+sin(1)+...+sin(8)+sin(9). This is - according to WolframAlpha indeed 1.95520.

Upvotes: 1

akuiper
akuiper

Reputation: 215117

You can vectorize it with numpy broadcasting:

np.sin(np.sum(a ** b[:,None], axis=1))

import numpy as np
a = np.arange(4)
b = np.arange(3)

np.sin(np.sum(a ** b[:,None], axis=1))
#array([-0.7568025 , -0.2794155 ,  0.99060736])

np.sin(np.sum(a ** b[0]))
#-0.7568024953079282

np.sin(np.sum(a ** b[1]))
#-0.27941549819892586

Upvotes: 2

Related Questions