Created
April 25, 2021 17:21
-
-
Save thomasaarholt/a7910dc4430bb1a53ad94bea63a6b8f3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def P1(P0=(0,0), Pc=(2,2), step=1): | |
"Get the point P1, the point to which one moves from P0 with a fixed step in the direction of Pc" | |
X0, Y0 = P0 | |
Xc, Yc = Pc | |
diffX = Xc - X0 | |
diffY = Yc - Y0 | |
magnitude = (diffX**2 + diffY**2)**0.5 | |
unitX = diffX / magnitude | |
unitY = diffY / magnitude | |
dPX = step*unitX | |
dPY = step*unitY | |
return X0 + dPX, Y0 + dPY | |
# tests | |
P1((0,0), (-1,-1)) # -0.7, -0.7 | |
P1((-1,-1), (-2, -1)) # -2, 1 | |
### Alternative approach using arrays - much shorter and clearer | |
import numpy as np | |
def P1_array(P0 = np.array([0,0]), Pc = np.array([2,2]), step=1): | |
"Get the point P1, the point to which one moves from P0 with a fixed step in the direction of Pc" | |
diff = Pc - P0 | |
return P0 + step * diff / np.linalg.norm(diff) | |
# test that both functions return the same | |
step = 3 | |
for xy0, xyc in np.random.random((10, 2, 2)): | |
np.testing.assert_array_almost_equal(P1(xy0, xyc, step), P1_array(xy0, xyc, step)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment