In this practice question, you have to create a Euclidean distance function euclidean_distance()
that takes two parameters of NumPy arrays and return euclidean distance.
The following equation gives the Euclidean distance formula:
import numpy as np def euclidean_distance(a, b): return np.sqrt(np.sum((a - b)*(a - b))) a = np.array([11, 12, 13, 14]) b = np.array([1, 2, 3, 4]) print(euclidean_distance(a, b))
Output
20.0
In NumPy, operations are performed element by element. So, when a - b
is computed, the 0th index element of array b is subtracted from the 0th index element of array a. In this way, other elements are subtracted.
a - b
gives [10, 10, 10, 10]
, when a - b
is multiplied with itself, it gives the square of (a - b). After that NumPy sum()
function is used to calculate the sum, and finally, NumPy sqrt()
is used to find the square root.
You can also test your Euclidean distance function using these two NumPy arrays:
A = np.array(range(100)) B = np.array(range(1, 101)) print(euclidean_distance(A, B)) Output 0