How can I find a random position between two points?

4.6k Views Asked by At

I have two points. I want to find a position that lays directly between those two points. So that if a line were drawn, this position would be exactly on this line.

For example, if I have the points (0,0) and (3,3), then (0,0), (1,1), (2.5, 2.5), (2.987, 2.987), (3,3), etc. would be valid points.

This seems like a simple concept, and I have searched, but I cannot seem to figure it out or find the answer.

How can I find a random point on a line?

2

There are 2 best solutions below

2
On BEST ANSWER

Briefly: generate a uniform random number $u$ between $0$ and $1$, and then evaluate $(1-u)p_1+up_2$, where $p_1$ and $p_2$ are your line segment's endpoints. The special case $u=1/2$ will of course generate the midpoint.

2
On

Let $(x_1,y_1)$ and $(x_2,y_2)$ be the edges:

if $x_1 \neq x_2$

1) The slope of the line is $a = \frac{ y_2 - y_1}{x_2 - x_1}$

2) Generate a random number $0 < n < 1$ and compute $x = (x_2 - x_1)n + x_1$.

3) For $x$, compute $y = a(x-x_1) + y_1$

if $x_1 = x_2$ (Thanks @J. M.)

1) $x = x_1 = x_2$

2) Generate a random number $0 < n < 1$ and compute $y = (y_2 - y_1)n + y_1$

There you have $(x,y)$.