如何在python中计算外部函数?

编程入门 行业动态 更新时间:2024-10-11 23:15:51
本文介绍了如何在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?

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

I found docs.scipy/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_arr和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

由于np.cos,np.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中计算外部函数?

本文发布于:2023-11-22 01:25:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615429.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   如何在   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!