Skip to content

Commit 2bd3a6d

Browse files
authored
Merge pull request #235 from Hemanth21k/q78_edit
Q.78 solution explained with reference
2 parents e26c40e + 93a34b4 commit 2bd3a6d

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

source/exercises100.ktx

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,18 +1090,35 @@ 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-
def distance(P0, P1, p):
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_faster(P0,P1,p):
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+
1108+
return d
1109+
1110+
print(distance_faster(P0, P1, p))
1111+
1112+
##--------------- OR ---------------##
1113+
def distance_slower(P0, P1, p):
10941114
T = P1 - P0
10951115
L = (T**2).sum(axis=1)
10961116
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
10971117
U = U.reshape(len(U),1)
10981118
D = P0 + U*T - p
10991119
return np.sqrt((D**2).sum(axis=1))
11001120

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))
1104-
print(distance(P0, P1, p))
1121+
print(distance_slower(P0, P1, p))
11051122

11061123
< q79
11071124
Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (★★★)

0 commit comments

Comments
 (0)