FLT_EPSILON = 1.19209290e-07 def get_weights2a(dists): total = 0.0 result = [0.0 for i in dists] for di in range(len(dists)): dist = dists[di] total += 1.0 / dist for i in range(len(result)): dist = dists[i] result[i] = (1.0 / dist) / total return result def get_weights2(dists): dmax = max(dists) if dmax <= FLT_EPSILON: # Float division error protection. return [1.0/len(dists) for i in dists] total = 0.0 result = [0.0 for i in dists] for di in range(len(dists)): dist = dists[di] total += 1.0 / dist if total <= FLT_EPSILON: # Float division error protection. return [1.0/len(dists) for i in dists] for i in range(len(result)): dist = dists[i] result[i] = (1.0 / dist) / total return result def run(): dists = [5.0,2.1,3.6,8.7,0.3] dists.sort() weights = get_weights2(dists) both = zip(dists,weights) for i in both: print i total = 0.0 for i in weights: total += i print total run()