我对 python 比较陌生,并且对优化和加速此功能的任何想法感兴趣。对于我正在做的数值计算,我必须调用它数万次,它占用了代码总计算时间的主要部分。我已经用 c 编写了这个,但我很想看看有什么技巧可以让它在 python 中运行得更快。
此代码根据http://en.wikipedia.org/wiki/Stereographic_projection计算 bigD 长度向量到 littleD 长度向量的立体投影。变量 a 是一个长度为 96 的 numpy 数组。
import numpy as np
def nsphere(a):
bigD = len(a)
littleD = 3
temp = a
# normalize before calculating projection
temp = temp/np.sqrt(np.dot(temp,temp))
# calculate projection
for i in xrange(bigD-littleD + 2,2,-1 ):
temp = temp[0:-1]/(1.0 - temp[-1])
return temp
#USAGE:
q = np.random.rand(96)
b = nsphere(q)
print b