Mr. Randy Tom
Mr. Randy Tom

Reputation: 331

Squared Distance vs Distance for measuring the distance between points

I'm using the following code to measure the distance between two 3d points.

import numpy as np

o1 = [-0.1695483, 0.08880598, -0.676]
o2 = [0.31333363, 0.06976531, -0.84899998]
o3 = [0.09157476, 0.05987176, -0.77499998]
o4 = [0.36830484, 0.10634459, -0.84100002]

squared_dist = np.sum((np.array(o3) - np.array(o1)) ** 2, axis=0)
print(squared_dist)

dist = np.linalg.norm(np.array(o3) - np.array(o3))

print(dist)

Which is most preferable to find the distance between the two 3d points?

Upvotes: 0

Views: 545

Answers (1)

KoKlA
KoKlA

Reputation: 988

The distance of a 3d vector is distance = (x ** 2 + y ** 2 + z ** 2) ** 0.5 . So linalg.norm is correct. To get the same result you need to do distance = squared_dist ** 0.5 . Also in your example you compare o3 with o1 and the other time o3 with o4

If you compare the correct vectors with each other and take the square root of the sum you get the same results

import numpy as np

o1 = [-0.1695483, 0.08880598, -0.676]
o2 = [0.31333363, 0.06976531, -0.84899998]
o3 = [0.09157476, 0.05987176, -0.77499998]
o4 = [0.36830484, 0.10634459, -0.84100002]

squared_dist = np.sum((np.array(o3) - np.array(o1)) ** 2, axis=0)
print(squared_dist ** 0.5)

dist = np.linalg.norm(np.array(o3) - np.array(o1))

print(dist)

Upvotes: 3

Related Questions