1

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
3
  • You probably mean a and b have length n... Commented Sep 26, 2017 at 15:01
  • 1
    In your edit, the sin(..) is the inner function. Do you want the sine of the sum or the sum of the sines? Commented Sep 26, 2017 at 15:04
  • oh, I want sum of the sines, sorry for not being precise.. the problem I want to solve is different from this, I tried making a much simplified version Commented Sep 26, 2017 at 15:08

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that looks very interesting!
1

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.

1 Comment

Oh yes, this seems to be exactly what I wanted.. its complexity is however a couple of level deeper than I'm used to, so I'm gonna have to play around with it some.. thanks alot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.