0

I'm trying to build a basic TSP solution in Python and I'm running into a bit of an issue when trying to calculate the total distance of each order of cities. The cities are created and stored as a randomly generated 2-Dimensional list; the inner lists each containing an x and y value, and the outer list containing the inner lists. I have a successful distance formula that takes 2 of these inner lists and finds the distance between them with:

def distance(pt1, pt2):
    return np.sqrt((pt2[0]-pt1[0]) ^ 2 + (pt2[1]-pt1[1]) ^ 2)

Which has been returning the correct answer in test cases. However, I also have a function to take in a list (intended to be used with the outer list) and calculates the total distance between all points using the above function as a helper. That function is as below:

def distTotal(points):
    total = 0
    for i in range(0, numCities-1):
        total += distance(points[i], points[i+1])

    return total

And the specific instance of it being called is below:

print(distTotal(cities))

Where "cities" is a randomly generated 2-D list. When testing this function, though, it returned "nan" ("not a number") each time. In debugging, it seems that the first time it attempts to run the distance function with in the distTotal function is when the value for "total" becomes equal to nan.

Any idea what I've done wrong here? Thanks

Jordan Lejman
  • 87
  • 1
  • 7

1 Answers1

0

The ^ operator is the XOR operator. Use instead the power operator **:

def distance(pt1, pt2):
    return np.sqrt((pt2[0]-pt1[0]) ** 2 + (pt2[1]-pt1[1]) ** 2)