[英]Speeding up summation for loop in python
我有以下瓶頸,想知道是否有人可以提出加速它的方法。
我有三個長度為N
列表x,y,z
。 我應用以下總結 。
def abs_val_diff(x1, x2, x3, y1, y2, y3):
""" Find the absolute value of the difference between x and y """
return py.sqrt((x1 - y1) ** 2.0 + (x2 - y2) ** 2.0 + (x3 - y3) ** 2.0)
R = 0.1
sumV = 0.0
for i in xrange(N):
for j in xrange(i + 1, N):
if R > abs_val_diff(x[i], y[i], z[i],
x[j], y[j], z[j]):
sumV += 1.0
我嘗試使用numpy數組,但是我做錯了什么,或者速度降低了大約2倍。
任何想法將不勝感激。
我相信您可以通過執行以下操作來更有效地利用numpy。 對函數進行一些小的修改以使用numpy.sqrt:
import numpy as np
def abs_val_diff(x1, x2, x3, y1, y2, y3):
""" Find the absolute value of the difference between x and y """
return np.sqrt((x1 - y1) ** 2.0 + (x2 - y2) ** 2.0 + (x3 - y3) ** 2.0)
然后使用完整數組調用:
res = abs_val_diff(x[:-1],y[:-1],z[:-1],x[1:],y[1:],z[1:])
然后,因為要為每個匹配項加1,所以您可以簡單地將查詢結果所得的數組長度作為結果:
sumV = len(res[R>res])
這讓numpy處理迭代。 希望對你有用
您實際上是否需要在函數中取平方根? 如果您要做的只是將結果與極限值進行比較,為什么不只是對比較的兩邊都做平方呢?
def abs_val_diff_squared(x1, x2, x3, y1, y2, y3):
""" Find the square of the absolute value of the difference between x and y """
return (x1 - y1) ** 2.0 + (x2 - y2) ** 2.0 + (x3 - y3) ** 2.0
R = 0.1
R_squared = R * R
sumV = 0.0
for i in xrange(N):
for j in xrange(i + 1, N):
if R_squared > abs_val_diff_squared(x[i], y[i], z[i],
x[j], y[j], z[j]):
sumV += 1.0
我還認為,將數據分類為八叉樹之類的東西應該可以節省更多的錢,因此您只需要查看附近的點,而不是將所有內容與所有內容進行比較,但這是我所不知道的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.