Optimized method for calculating cosine distance in Python
问题 I wrote a method to calculate the cosine distance between two arrays: def cosine_distance(a, b): if len(a) != len(b): return False numerator = 0 denoma = 0 denomb = 0 for i in range(len(a)): numerator += a[i]*b[i] denoma += abs(a[i])**2 denomb += abs(b[i])**2 result = 1 - numerator / (sqrt(denoma)*sqrt(denomb)) return result Running it can be very slow on a large array. Is there an optimized version of this method that would run faster? Update: I've tried all the suggestions to date,