我在ipython中尝试了以下代码:我想使用vectorize并给出函数prox(x,tau)。 但是lambda中的第一个值总是两次。
In [32]: a = np.array([[ 1., 2.],[ 3., 4.]]) In [33]: def prox(x, tau): ...: print x, tau ...: if x >= tau: ...: print "first" ...: return x-tau ...: if -tau <= x and x <= tau: ...: print "second" ...: return 0.0 ...: if x <= -tau: ...: print "third" ...: return x+tau In [34]: b = np.vectorize(lambda x: prox(x, 2))(a[:,1:]) In [35]: b 2.0 2 first 2.0 2 first 4.0 2 first为什么第35行是两次打印相同的值? 2.0 2
I tried in ipython following code: I want to use vectorize and give the function prox(x,tau). But the first value in lambda comes always two times.
In [32]: a = np.array([[ 1., 2.],[ 3., 4.]]) In [33]: def prox(x, tau): ...: print x, tau ...: if x >= tau: ...: print "first" ...: return x-tau ...: if -tau <= x and x <= tau: ...: print "second" ...: return 0.0 ...: if x <= -tau: ...: print "third" ...: return x+tau In [34]: b = np.vectorize(lambda x: prox(x, 2))(a[:,1:]) In [35]: b 2.0 2 first 2.0 2 first 4.0 2 firstWhy in line 35 is two times printed the same value? 2.0 2
最满意答案
如果未指定otypes ,则vectorize将使用第一个值执行测试计算,并使用它来确定它返回的数组的dtype 。 因此,第一项的双重评估。
通常额外的计算是不重要的。 不过要小心。 如果该初始计算返回一个整数(例如标量0),则返回的数组也将是整数,从而在后续计算中丢失任何浮点值。
有关更多详细信息,请查看vectorize的文档。
vectorize是不确定的 - 由非预期的整数otype产生的错误。 我在其他SO问题中看到过这个错误。
If you don't specify otypes, then vectorize performs a test calculation with the first value, and uses that to determine the dtype of the array it returns. Hence the double evaluation of the first item.
Usually that extra calculation is unimportant. But be careful. If that initial calculation returns an integer (e.g. scalar 0) the returned array will also be integer, loosing any float values in subsequent calculations.
For more details review the docs for vectorize.
vectorize is indeterminate - An error produced by an unintended integer otype. I've seen this error in other SO questions.
更多推荐
发布评论