Finding sum of a function u=n*x*y for n =[ 0 to N] ; x and y are some array

Question:

I want to write a code using python for solving a function such as follows :

u = sum(n*x*y) for n=[0 to N]

Let’s say x = [1,2,3,4,5] and y =[6,7,8,9,10] and n= [1,2,..100]

I expect an output like this :

u = [u0, u1, u2, u3..]; where u0 = sum([nn*x[0]*y[0] for nn in n]) and similarly for u1,u2..

Thought of doing this :

u = []
For i in n:
    j = sum([i*x*y])
    u.append(j)

Now of course the problem I have is idk how I can go about defining x and y in the loop. Probably need to use another for loop or while loop, or some if/else, but I’m not able to wrap my mind around it for some reason. Pretty new to coding so any help would be appreciated.

Asked By: nofugz

||

Answers:

I believe you want:

uu = sum( nn*(sum(xx*yy) for xx,yy in zip(x,y)) for nn in n )

which is similar but better than:

uu = sum( nn*(sum(x[i]*y[i]) for i in range(len(x))) for nn in n )

FOLLOWUP

u = [sum([nn*xx*yy for nn in n]) for xx,yy in zip(x, y)]
Answered By: Tim Roberts

Do you want:

x = [1,2,3,4,5]
y = [6,7,8,9,10]
n = [1,2,100]

u = [sum([nn*x[i]*y[i] for nn in n]) for i in range(len(x))]

# or
u = [sum([nn*x_i*y_i for nn in n]) for x_i, y_i in zip(x, y)]

Output:

[618, 1442, 2472, 3708, 5150]

version:

x = np.array([1,2,3,4,5])
y = np.array([6,7,8,9,10])
n = np.array([1,2,100])

u = ((x*y)*n[:,None]).sum(0)

Output:

array([ 618, 1442, 2472, 3708, 5150])
Answered By: mozway