如何在python中计算外部函数? [英] How can I calculate an outer function in python?

查看:136
本文介绍了如何在python中计算外部函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个像func(x,y)= cos(x)+ sen(y)+ x * y这样的随机函数,如何将其应用于2个数组中的所有元素对?

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?

我找到了 https://docs.scipy.org /doc/numpy/reference/generation/numpy.outer.html 和 发现所有基本操作都有外部功能.但是,如果我想使用自定义功能怎么办?

I found https://docs.scipy.org/doc/numpy/reference/generated/numpy.outer.html and discovered that there are outer functions for all the basic operations. But what if I want to do it with a custom function?

想象array1为[1,2],array2为[3,4],我想应用的函数称为f(float,float)

Imagine array1 is [1,2], array2 is [3,4] and the function I wanted to apply is called f(float, float)

预期输出为

[f(1,3)f(1,4)

[f(1,3) f(1,4)

f(2,3)f(2,4)]

f(2,3) f(2,4)]

推荐答案

只要确保以正确广播的方式编写函数,就可以做到

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)

将其应用于两个一维数组x_arry_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

由于np.cosnp.sin+*在整个阵列中广播和矢量化.

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

至于它是否不广播?好吧,有些人可能会建议np.vectorize,但是您要记住很多棘手的事情,例如保持一致的输出dtype且没有副作用.如果您的函数没有广播,我建议您仅使用列表推导:

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])

这篇关于如何在python中计算外部函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆