Skip to content

Commit 58ed6a9

Browse files
authored
Merge pull request #229 from yangwu1227/broadcast-solution-exercise-79
broadcasting solution exercise 79
2 parents 4090dc6 + adf896f commit 58ed6a9

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

source/exercises100.ktx

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,6 +1118,32 @@ P1 = np.random.uniform(-10,10,(10,2))
11181118
p = np.random.uniform(-10, 10, (10,2))
11191119
print(np.array([distance(P0,P1,p_i) for p_i in p]))
11201120

1121+
# Author: Yang Wu (Broadcasting)
1122+
def distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray:
1123+
x_0, y_0 = p.T # Shape -> (n points, )
1124+
x_1, y_1 = p_1.T # Shape -> (n lines, )
1125+
x_2, y_2 = p_2.T # Shape -> (n lines, )
1126+
1127+
# Displacement vector coordinates from p_1 -> p_2
1128+
dx = x_2 - x_1 # Shape -> (n lines, )
1129+
dy = y_2 - y_1 # Shape -> (n lines, )
1130+
1131+
# The 'cross product' term
1132+
cross_term = x_2 * y_1 - y_2 * x_1 # Shape -> (n lines, )
1133+
1134+
# Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines)
1135+
numerator = np.abs(
1136+
dy[np.newaxis, :] * x_0[:, np.newaxis]
1137+
- dx[np.newaxis, :] * y_0[:, np.newaxis]
1138+
+ cross_term[np.newaxis, :]
1139+
)
1140+
denominator = np.sqrt(dx**2 + dy**2) # Shape -> (n lines, )
1141+
1142+
# Shape (n points, n lines) / (1, n_lines) -> (n points, n lines)
1143+
return numerator / denominator[np.newaxis, :]
1144+
1145+
distance_points_to_lines(p, P0, P1)
1146+
11211147
< q80
11221148
Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)
11231149

0 commit comments

Comments
 (0)