简体   繁体   中英

How can I add two functions together in Python 3?

For example I have two functions expressed with two lists:

x_1 = [0, 1, 2, 3, 4, 5]
y_1 = [2, 4, 1, 5, 1, 2]

x_2 = [2, 3, 4, 5, 6, 7]
y_2 = [2, 4, 1, 5, 1, 2]

and the result should be

x = [0, 1, 2, 3, 4, 5, 6, 7]
y = [2, 4, 3, 9, 2, 7, 1, 2]

Here I set the x values in the integer lattice but it is not necessary. But I guess one solution could be normalizing them onto the lattice and then add them.

Is there any simple method to do this? Numpy and Scipy are both available.

Thanks!


A simple illustration 在此输入图像描述

Naive implementation:

x_1 = [0, 1, 2, 3, 4, 5]
y_1 = [2, 4, 1, 5, 1, 2]

x_2 = [2, 3, 4, 5, 6, 7]
y_2 = [2, 4, 1, 5, 1, 2]

f1 = dict(zip(x_1, y_1))
f2 = dict(zip(x_2, y_2))

x = list(set(f1.keys()) | set(f2.keys()))
y = [f1.get(k, 0) + f2.get(k, 0) for k in x]

print x
print y

Result:

[0, 1, 2, 3, 4, 5, 6, 7]
[2, 4, 3, 9, 2, 7, 1, 2]

numpy has a 1d interpolation function, and scipy has a more general one(s).

A simple approach with np.interp :

x1,y1=[0,1,2,3,4,5],[2,4,1,5,1,2]
x2,y2=[2,3,4,5,6,7],[2,4,1,5,1,2]
x3 = np.arange(x1[0],x2[-1]+1)  # or latice of your choice
np.interp(x3,x1,y1,0,0) + np.interp(x3,x2,y2,0,0)

producing:

array([ 2.,  4.,  3.,  9.,  2.,  7.,  1.,  2.])

I told interp to return 0 for values outside the x1 range, which seems to fit your addition scheme well.

A couple of other ways of constructing x3 :

Join the 2 lists, and ask for the unique values (sorted):

x3=np.unique(x1+x2)

or if the x might already be arrays, concatenate them first:

x3=np.unique(np.concatenate([x1,x2]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM