【问题标题】:numpy: point sumnumpy:点总和
【发布时间】:2011-12-17 16:51:40
【问题描述】:
>>> from pandac.PandaModules import Vec3
>>> import numpy
>>> l = []
>>> l.append( Vec3(1,1,1) )
>>> l.append( Vec3(1,1,1) )
>>> l.append( Vec3(1,1,1) )
>>> Vec3(1,1,1)+Vec3(1,1,1)
Vec3(2, 2, 2)
>>> sum(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'libpanda.Vec3'
>>> numpy.sum(l)
9.0
>>> 

我想要一些快速(快速 == 不是纯 python 中的循环,而是 numpy 速度)方法来实现:

>>> my_smart_sum(l)
Vec3(3,3,3)

【问题讨论】:

  • 好的,我发现了这个方法:reduce(lambda x,y:x+y, l) 有一些缺点?
  • 有一个缺点,最好解释here

标签: python numpy panda3d


【解决方案1】:

试试这个:

sum(l, start=Vec3(0,0,0))

或者,使用 numpy,这个:

numpy.sum(l, axis=0)

速度取决于向量加法的实现。您应该使用timeit 来确定哪种方法最快。这可能看起来像这样:

python -m timeit "import numpy; foo = [[1,1,1],[1,1,1]]" "numpy.sum(foo, axis=0)"
10000 loops, best of 3: 46.5 usec per loop

您传递的第一个字符串是设置语句 - 这不会包含在计时中。您传递的第二个字符串是您实际想要计时的代码。我对pandac 一无所知,但有时使用Cython 可以大大加快数字运算循环的速度。

【讨论】:

  • 和 start 就可以了。因为我需要 Vec3 的返回值,并且 numpy.sum 返回一个 numpy 数组。 pandac 是一个用 c++ 编写并用 python 包装的渲染引擎,所以我认为没问题。
  • 使用reduce有什么缺点吗?
猜你喜欢
  • 2017-07-08
  • 1970-01-01
  • 2013-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 2012-01-28
  • 1970-01-01
相关资源
最近更新 更多