您的位置:首页 > 编程语言 > Python开发

<PY>计算范数及效率

2015-09-29 10:34 387 查看
from timeit import Timer
def calcDistance0(xj, xk, p=2): # default:L2
if len(xj) != len(xk): return 'Error:length not match'
return sum([abs(xj[i] - xk[i]) ** p for i in range(len(xj))]) ** (1.0 / p)

def calcDistance00(xj, xk, p=2): # default:L2
pp=1.0 / p
if len(xj) != len(xk): return 'Error:length not match'
return sum([abs(xj[i] - xk[i]) ** p for i in range(len(xj))]) ** pp

calcDistance1 = lambda xj, xk, p=2: sum([abs(xj[i] - xk[i]) ** p for i in range(len(xj))]) ** (1.0 / p) if len(
xj) == len(xk) else 'Error:length not match'
calcDistance2 = lambda xj, xk, p=2: pow(sum(map(lambda j, k: pow(abs(j - k), p), xj, xk)), 1.0 / p) if len(xj) == len(
xk) else 'Error:length not match'

print(Timer('calcDistance0((1,1,1,1),(4,4,4,4))', "from __main__ import calcDistance0").timeit(number=10000000))
print(Timer('calcDistance00((1,1,1,1),(4,4,4,4))', "from __main__ import calcDistance00").timeit(number=10000000))
print(Timer('calcDistance1((1,1,1,1),(4,4,4,4))', "from __main__ import calcDistance1").timeit(number=10000000))
print(Timer('calcDistance2((1,1,1,1),(4,4,4,4))', "from __main__ import calcDistance2").timeit(number=10000000))


运行结果

C:\Python34\python.exe E:/Test/calcDistance.py

30.547852301933165

29.285436166684008

30.837739172868808

30.192122066862268

效率都差不多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息