0

这是有关如何使用的示例numpy.meshgrid

x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)

如果我在上面有一个meshgridlike xxyy但我的函数是一个常规函数,而不是vectorized,f(x,y)例如,常规math.sin函数怎么办?

我知道我可以遍历list of lists, xxyy但我想尝试模拟vectorized代码。

4

1 回答 1

1

如果您不在乎速度,可以使用numpy.vectorize()

import numpy as np
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)

import math
def f(x, y):
    return math.sin(x**2 + y**2) / (x**2 + y**2)

np.allclose(np.vectorize(f)(xx, yy), z)
于 2018-02-20T00:54:11.613 回答