-3

How to calculate distance between 2 vectors using Euclidian distance formula, but without using linalg.norm?

Here is the code I have written, which works. How would I get the same effect without using linalg.norm?

import numpy as np

def distance(arr1,arr2):    
    dist = np.linalg.norm(arr1 - arr2)
    return dist
cigien
  • 57,834
  • 11
  • 73
  • 112

2 Answers2

0

Using numpy.linalg.norm is easier because you are relying on a function that has already been written.

The purpose of the exercise is to improve your programming and mathematical knowledge.

Start with the Euclidean distance formula and write a function that will perform each step necessary in the calculation.

# Calculate the Euclidean distance between two points (P and Q)
def calculate_Euclidean_distance(point_P_list, point_Q_list):
    log.debug('Enter calculate_Euclidean_distance')
    log.info('point_P_list: (%s)' % ', '.join(map(str, point_P_list)))
    log.info('point_Q_list: (%s)' % ', '.join(map(str, point_Q_list)))

    # Store the sum of squared distances between coordinates
    sum_of_coordinate_distance_squared = 0
    # For each coordinate p and q in the points P and Q square the difference
    for p, q in zip(point_P_list, point_Q_list):
        distance_pq_squared = (p - q) ** 2
        sum_of_coordinate_distance_squared += distance_pq_squared

    # The distance between points P and Q is the square root of the sum of coordinate differences squared
    distance_PQ = math.sqrt(sum_of_coordinate_distance_squared)
    log.info('distance_PQ: ' + str(distance_PQ))
[2019-09-27 15:03:33,257] [main] Start example.py execution
[2019-09-27 15:03:33,259] [calculate_Euclidean_distance] Enter calculate_Euclidean_distance
[2019-09-27 15:03:33,260] [calculate_Euclidean_distance] point_P_list: (9, 20)
[2019-09-27 15:03:33,261] [calculate_Euclidean_distance] point_Q_list: (18, 8)
[2019-09-27 15:03:33,261] [calculate_Euclidean_distance] distance_PQ: 15.0
[2019-09-27 15:03:33,261] [main] End example.py execution
0

solution:

import numpy as np
def distance(arr1,arr2):    
   dist = np.sqrt(sum([(i-j)**2 for i,j in zip(arr1,arr2)]))

   return dist
  • 3
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Aug 28 '22 at 00:20