Skip to content

Instantly share code, notes, and snippets.

@thomasaarholt
Created April 25, 2021 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasaarholt/a7910dc4430bb1a53ad94bea63a6b8f3 to your computer and use it in GitHub Desktop.
Save thomasaarholt/a7910dc4430bb1a53ad94bea63a6b8f3 to your computer and use it in GitHub Desktop.
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