您的代码已经看起来很好了,但是这里还有一些想法。
这是一个一行的代码。
它比您的版本稍微慢一些。
def randvector2(n):
return np.exp((2.0j * np.pi) * np.random.rand(n, 1)).view(dtype=np.float64)
I get these timings for n=10000
Yours:
1000 loops, best of 3: 716 µs per loop
我的简化版:
1000 loops, best of 3: 834 µs per loop
如果速度是一个问题,你的方法确实非常好。
另一个答案展示了如何使用hstack。
那个方法也很好。
这里有另一种版本,与你的略有不同,但速度稍微快一点。
def randvector3(n):
x = np.empty([n,2])
theta = (2 * np.pi) * np.random.rand(n)
np.cos(theta, out=x[:,0])
np.sin(theta, out=x[:,1])
return x
这让我知道了时间安排:
1000 loops, best of 3: 698 µs per loop
如果您可以访问numexpr,以下方法更快(至少在我的机器上)。
import numexpr as ne
def randvector3(n):
sample = np.random.rand(n, 1)
c = 2.0j * np.pi
return ne.evaluate('exp(c * sample)').view(dtype=np.float64)
这让我知道了时间安排:
1000 loops, best of 3: 366 µs per loop
说实话,如果我写的不是极度性能密集型的东西,我会做跟你一样的事情。
这让读者很清楚你的意图。
用hstack的版本也很好用。
另外一个小提示:
当n=10时,我的单行版本最快。
当n=10000000时,快速的纯numpy版本最快。
np
。 - Alejandro Sazo