I am plotting random points on a graph. I want to find the Eucildean distance from every point to another in a list.
Previous result/attempt can be viewed here
I generate 4 random numbers between 0 and 10 for the x and y coordinates, and then pair them using np.array. I need use distance formula and a nested loop to calculate the distance between two points in the list. This generates 8 values, which I assume is the distances. As there is 4 points, there should be 6 distances between the points.
Am I programming in the distance forumla incorrectly? Or am I defining the points incorrectly?
Code below
import numpy as np
import matplotlib.pyplot as plt
import random
import math
dist = []
x = [random.uniform(1, 10) for n in range(4)]
y = [random.uniform(1, 10) for n in range(4)]
plt.scatter(x, y)
plt.show()
pairs = np.array([x, y])
def distance(x, y):
return math.sqrt((x[0]-x[1])**2 + (y[0]-y[1])**2)
for x in pairs:
for y in pairs:
d = distance(x, y)
dist.append(d)
print(pairs)
You can try the code below to achieve calculating the distance between each pair of points
import random
import math
dist = []
x = [random.uniform(1, 10) for n in range(4)]
y = [random.uniform(1, 10) for n in range(4)]
pairs = list(zip(x,y))
def distance(x, y):
return math.sqrt((x[0]-x[1])**2 + (y[0]-y[1])**2)
for i in range(len(pairs)):
for j in range(i+1,len(pairs)):
dist.append(distance(pairs[i],pairs[j]))
print(dist)