如何在python2.7中使用vectorize numpy函数?(How to use the vectorize numpy function in python2.7?)

编程入门 行业动态 更新时间:2024-10-09 09:22:25
如何在python2.7中使用vectorize numpy函数?(How to use the vectorize numpy function in python2.7?)

我在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 first

Why 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.

更多推荐

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

发布评论

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

>www.elefans.com

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