Euclidean distance formula is a very popular formula in mathematics. This is used to calculate the distance between two points in a two dimensional plane.

Problem Statement

There are n points in a two dimensional plane. The requirement is to find the nearest point/s to a point P in the two dimensional plane.

Solution

  • Get the value to n
  • Get the values of all the n points (x,y)
  • Get the value of point P
  • Find the distance of each of the points to the point P.
  • Find the point/s which has the shortest distance to point P and print those points.

The Euclidean formula

distance2 = (x2 – x1)2 + (y2 – y1)2

distance = square root of the above value.

The python program is given below.

import math
n = int(input("Enter the number of points\n"))
line_points = []
for i in range(n):
x, y = input("Enter the coordinate x,y \n").split(',')
coordinates = [int(x), int(y)]
line_points.append(coordinates)
xp, yp = input("Enter the coordinate of center point P \n").split(',')
pt = [int(xp), int(yp)]
dist = []
c = 0
least_distance = 0
for i in range(n):
xa = int(line_points[i][0])
ya = int(pt[0])
xb = int(line_points[i][1])
yb = int(pt[1])
# Euclidean distance formula
distance = math.sqrt(((xa ya)**2) + ((xb yb)**2))
dist.append(distance)
# Finding the least distance value
if distance <= least_distance:
least_distance = distance
# Finding the points with least distance
c_list = list()
for i in range(len(dist)):
if dist[i] == least_distance:
c_list.append(line_points[i])
print("Points which are closer to the point P : ", tuple(c_list))