How to make a code faster to calculate the linear distances from the point Python?

Question:

Here is the code:

Outputs = []

for X2, Y2 in X:
    Color_Gradient = 0
    Lowest = 0
    for X1, Y1, grad in zip(Velocity_Momentum[:, 0], Velocity_Momentum[:, 1], Color):
        XD = X2 - X1
        YD = Y2 - Y1
        Distance = math.sqrt((XD * XD) + (YD * YD))
        if Lowest == 0 or Lowest > Distance:
            Lowest = Distance
            Color_Gradient = grad
    Outputs.append(Color_Gradient)
    print("X2 = ", X2, " Y2 = ", Y2, " Color = ", Color_Gradient)

Here X.shape = (572, 2) Velocity_Momentum = (1000000, 2) Color = (1000000,).

Please let me know how to make it faster. I have tried the code above and it is very very slow. That is not good since I am trying to get the result faster.
Please let me know.

Asked By: Jaffer Wilson

||

Answers:

It looks like you are using numpy arrays. With numpy, it is faster to use vectorized operations on whole arrays at the same time, compared to loops. It also usually gives cleaner code.

As I understand it, you want to extract the color corresponding to the smallest (euclidean) distance to a specific point.

Outputs = []

for X2, Y2 in X:
    XD = X2 - Velocity_Momentum[:, 0]
    YD = Y2 - Velocity_Momentum[:, 1]
    Distance = (XD * XD) + (YD * YD)
    Color_Gradient = Color[Distance.argmin()]
    Outputs.append(Color_Gradient)
    print("X2 = ", X2, " Y2 = ", Y2, " Color = ", Color_Gradient)
Answered By: Rob