【发布时间】:2019-12-17 15:44:46
【问题描述】:
我希望能够在标量 numpy 1-D 数组或 numpy 2-D 数组上应用通用函数。 例子是
def stress2d_lefm_cyl(KI, r, qdeg) :
"""Compute stresses in Mode I around a 2D crack, according to LEFM
q should be input in degrees"""
sfactor = KI / sqrt(2*pi*r)
q = radians(qdeg)
q12 = q/2; q32 = 3*q/2;
sq12 = sin(q12); cq12 = cos(q12);
sq32 = sin(q32); cq32 = cos(q32);
af11 = cq12 * (1 - sq12*sq32); af22 = cq12 * (1 + sq12*sq32);
af12 = cq12 * sq12 * cq32
return sfactor * np.array([af11, af22, af12])
def stress2d_lefm_rect(KI, x, y) :
"""Compute stresses in Mode I around a 2D crack, according to LEFM
"""
r = sqrt(x**2+y**2) <-- Error line
q = atan2(y, x)
return stress2d_lefm_cyl(KI, r, degrees(q))
delta = 0.5
x = np.arange(-10.0, 10.01, delta)
y = np.arange(0.0, 10.01, delta)
X, Y = np.meshgrid(x, y)
KI = 1
# I want to pass a scalar KI, and either scalar, 1D, or 2D arrays for X,Y (of the same shape, of course)
Z = stress2d_lefm_rect(KI, X, Y)
TypeError: only size-1 arrays can be converted to Python scalars
(我的意思是用它来绘制等高线图)。 如果我现在改成
def stress2d_lefm_rect(KI, x, y) :
"""Compute stresses in Mode I around a 2D crack, according to LEFM
"""
r = lambda x,y: x**2 + y**2 <-- Now this works
q = lambda x,y: atan2(y, x) <-- Error line
return stress2d_lefm_cyl(KI, r(x,y), degrees(q(x,y)))
Z = stress2d_lefm_rect(KI, X, Y)
TypeError: only size-1 arrays can be converted to Python scalars
归结为
x = np.array([1.0, 2, 3, 4, 5])
h = lambda x,y: atan2(y,x) <-- Error
print(h(0,1)) <-- Works
print(h(x, x)) <-- Error
1.5707963267948966
TypeError: only size-1 arrays can be converted to Python scalars
发布了一个“类似”问题,Most efficient way to map function over numpy array
区别在于:
1. 我必须(或可能更多)参数(x,y),它们应该具有相同的形状。
2. 我还结合了一个标量参数 (KI)。
3.atan2 似乎比**2 更不“宽容”。我的意思是使用通用函数。
4. 我正在链接两个函数。
这可以解决吗? 也许第 2 点可以通过将结果乘以其他地方来克服。
【问题讨论】:
-
math.tan仅适用于标量值。np.tan适用于数组输入。 -
你真的只需要使用 numpy 函数,它就会按预期工作。也许用这个? docs.scipy.org/doc/numpy/reference/generated/numpy.arctan2.html
标签: python arrays function numpy lambda