Python fit line to high dimensional points and sample between them

51 Views Asked by At

I have two high-dimensional points (for this example let's consider 5 dimensional).

p0 = [2 4 1 3 9]
p1 = [5 2 1 0 8]

I want to fit a line (hyperplane) between them and then sample a random point (p2) from the line that is between the two original points. p2 is not necessarily the midpoint between the two points, but anywhere along the line. The image below shows what that would look like in 2-dimesions. How would I do that in python? Thanks!

enter image description here

1

There are 1 best solutions below

1
Michael Cao On BEST ANSWER

You can parametrize this line segment as p2 = p0 + t*(p1-p0) with parameter t in range [0, 1].

Doing this in code:

import numpy as np

p0 = [2, 4, 1, 3, 9]
p1 = [5, 2, 1, 0, 8]

p0 = np.array(p0)
p1 = np.array(p1)

dp = p1 - p0

t = np.random.rand(1)[0]

p2 = p0 + t*dp
print(p2)

Note that np.random.rand() selects from range [0, 1), so there is some small chance for p2 == p0.