Skip to content

Commit 3d136da

Browse files
committed
Q.78 solution expalined
1 parent 2b81a8e commit 3d136da

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

source/exercises100.ktx

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,17 +1090,37 @@ Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to comp
10901090
No hints provided...
10911091

10921092
< a78
1093+
P0 = np.random.uniform(-10,10,(10,2))
1094+
P1 = np.random.uniform(-10,10,(10,2))
1095+
p = np.random.uniform(-10,10,( 1,2))
1096+
1097+
def distance(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)
1113+
return d
1114+
print(distance(P0, P1, p))
1115+
1116+
##--------------- OR ---------------##
10931117
def distance(P0, P1, p):
10941118
T = P1 - P0
10951119
L = (T**2).sum(axis=1)
10961120
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
10971121
U = U.reshape(len(U),1)
10981122
D = P0 + U*T - p
10991123
return np.sqrt((D**2).sum(axis=1))
1100-
1101-
P0 = np.random.uniform(-10,10,(10,2))
1102-
P1 = np.random.uniform(-10,10,(10,2))
1103-
p = np.random.uniform(-10,10,( 1,2))
11041124
print(distance(P0, P1, p))
11051125

11061126
< q79

0 commit comments

Comments
 (0)