How can I calculate an outer function in python?

后端 未结 3 2153
醉酒成梦
醉酒成梦 2021-01-07 06:18

If I have a random function like func(x,y) = cos(x) + sen(y) + x*y how can I apply it to all the pairs of elements in 2 arrays?

I found https://docs.scipy.org/doc/nu

3条回答
  •  长情又很酷
    2021-01-07 07:08

    As long as you make sure to write your function in such a way that it broadcasts properly, you can do

    f(x_arr[:, None], y_arr)
    

    to apply it to all pairs of elements in two 1-dimensional arrays x_arr and y_arr.

    For example, to write your example function in a way that broadcasts, you'd write it as

    def func(x, y):
        return np.cos(x) + np.sin(y) + x*y
    

    since np.cos, np.sin, +, and * broadcast and vectorize across arrays.


    As for if it doesn't broadcast? Well, some might suggest np.vectorize, but that has a lot of tricky things you have to keep in mind, like maintaining a consistent output dtype and not having side effects. If your function doesn't broadcast, I'd recommend just using list comprehensions:

    np.array([[f(xval, yval) for yval in y_arr] for xval in x_arr])
    

提交回复
热议问题