Skip to content

Commit 44df2b0

Browse files
committed
simplified answer.78
1 parent dbb5419 commit 44df2b0

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

source/exercises100.ktx

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1095,22 +1095,18 @@ P1 = np.random.uniform(-10,10,(10,2))
10951095
p = np.random.uniform(-10,10,( 1,2))
10961096

10971097
def distance_faster(P0,P1,p):
1098-
'''
1099-
Author: Hemanth Pasupuleti
1100-
Reference: https://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
1101-
1102-
---- Explainable solution - Slightly Faster as number of lines scale up exponentially ----
1103-
'''
1104-
v = P1- P0 # Shape: (n_lines,2), Compute: [(x2-x1) (y2-y1)]
1105-
v[:,[0,1]] = v[:,[1,0]] # Shape: (n_lines,2), Swap along axis to Compute: [(y2-y1) (x2-x1)]
1106-
v[:,1]*=-1 # Shape: (n_lines,2), Compute: [(y2-y1) -(x2-x1)]
1107-
norm = np.linalg.norm(v,axis=1) # Shape: (n_lines,), Compute: sqrt((x2-x1)**2 + (y2-y1)**2)
1108-
r = P0 - p # Shape: (n_lines,2), Compute: [(x1-x0) (y1-y0)]
1109-
1110-
# np.einsum('ij,ij->i',r,v) is equivalent to np.multiply(r,v)).sum(axis=1) which is scalar product of two matrices across axis 1.
1111-
1112-
d = np.abs(np.einsum("ij,ij->i",r,v)) / norm # Shape: (n_lines,), Compute: d = |(x1-x0)*(y2-y1)-(y1-y0)*(x1-x0)|/sqrt((x2-x1)**2 + (y2-y1)**2)
1098+
#Author: Hemanth Pasupuleti
1099+
#Reference: https://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
1100+
1101+
v = P1- P0
1102+
v[:,[0,1]] = v[:,[1,0]]
1103+
v[:,1]*=-1
1104+
norm = np.linalg.norm(v,axis=1)
1105+
r = P0 - p
1106+
d = np.abs(np.einsum("ij,ij->i",r,v)) / norm
1107+
11131108
return d
1109+
11141110
print(distance_faster(P0, P1, p))
11151111

11161112
##--------------- OR ---------------##
@@ -1121,6 +1117,7 @@ def distance_slower(P0, P1, p):
11211117
U = U.reshape(len(U),1)
11221118
D = P0 + U*T - p
11231119
return np.sqrt((D**2).sum(axis=1))
1120+
11241121
print(distance_slower(P0, P1, p))
11251122

11261123
< q79

0 commit comments

Comments
 (0)