“如果” Python 中用于数组的函数
我有这个函数:
def q(x,y):
r2 = (x/2.)**2 + (2.0*y)**2
if (r2 > 0.04):
return 0.
else:
return 1.5
我想使用类似的东西来调用它
from pylab import *
dl=0.025
X, Y = mgrid[-0.5:0.5:dl, -0.5:0.5:dl]
g(X,Y)
,但显然这会在比较中产生错误。
是否可以在无需为 X 和 Y 进行 for 循环的情况下完成此操作? 因为如果我想为两个双精度调用 q(x,y),则必须针对这种情况重新实现 for 循环...
编辑: (将其添加到问题中,因为它对于评论而不是答案,但它可能会帮助其他人回答。)
看来 pylab.mgrid 与 numpy.mgrid 相同。
针对numpy
进行调整,此代码
import numpy
def q(x,y):
r2 = (x/2.)**2 + (2.0*y)**2
if (r2 > 0.04):
return 0.
else:
return 1.5
dl=0.025
X, Y = numpy.mgrid[-0.5:0.5:dl, -0.5:0.5:dl]
q(X,Y)
给出了此错误
if (r2 > 0.04):
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
I have this function:
def q(x,y):
r2 = (x/2.)**2 + (2.0*y)**2
if (r2 > 0.04):
return 0.
else:
return 1.5
and I want to call it using something like
from pylab import *
dl=0.025
X, Y = mgrid[-0.5:0.5:dl, -0.5:0.5:dl]
g(X,Y)
but obviously this gives an error in the comparison.
Can this be done without having to make a for cycle for X and Y?
Because if I want to call q(x,y) for two doubles, the for cycle must be reimplemented for that case...
Edit: (Adding this to the question as it is too long for a comment and not an answer, but it may help others answer.)
It appears pylab.mgrid
is the same as numpy.mgrid
.
Adjusted for numpy
, this code
import numpy
def q(x,y):
r2 = (x/2.)**2 + (2.0*y)**2
if (r2 > 0.04):
return 0.
else:
return 1.5
dl=0.025
X, Y = numpy.mgrid[-0.5:0.5:dl, -0.5:0.5:dl]
q(X,Y)
gives this error
if (r2 > 0.04):
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
表达式
r2> 0.04
计算结果为布尔值的 NumPy 数组,因此您不能在if
语句中使用它。不过,您可以将其自动重新解释为数字:The expression
r2 > 0.04
evaluates to a NumPy array of Boolean values, so you can't use it in anif
statement. You can have it automatically reinterpreted as numbers, though:您可以使用 map 将函数应用于每对元素。
You may use map to apply your function to each couple of elements.