Equidistant points between two points?

Viewed 10772

I am trying to know equidistant points between two points. For example:

p1 = (1,1)
p2 = (5,5)

The answer that I am expecting is:

def getEquidistantPoints(p1, p2, HowManyParts):
    #some code
    return (array with points)

In this example, with p1, and p2:

A = getEquidistantPoints(p1,p2,4)
A = [(1,1),(2,2),(3,3),(4,4),(5,5)]

Always will be a straight line. HowManyParts in this case is the whole distance that is divided
something like numpy.linspace() but in two dimensions.

3 Answers

Thanks to linearity of the line connecting two points, you can simply use numpy.linspace for each dimension independently:

import numpy

def getEquidistantPoints(p1, p2, parts):
    return zip(numpy.linspace(p1[0], p2[0], parts+1),
               numpy.linspace(p1[1], p2[1], parts+1))

For example:

>>> list(getEquidistantPoints((1,1), (5,5), 4))
>>> [(1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0), (5.0, 5.0)]

A pure Python solution using linear interpolation:

First create a linear interpolation function:

def lerp(v0, v1, i):
    return v0 + i * (v1 - v0)

and then just use this to interpolate between the x and y coordinates:

def getEquidistantPoints(p1, p2, n):
    return [(lerp(p1[0],p2[0],1./n*i), lerp(p1[1],p2[1],1./n*i)) for i in range(n+1)]

and a test with your values:

>>> getEquidistantPoints((1,1), (5,5), 4)
[(1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0), (5.0, 5.0)]

The easiest way is to use an iterable (tuple, list, etc.). to specify the start and the end arguments of numpy.linspace:

p1 = (1,1)
p2 = (5,5)
HowManyParts = 4
A = np.linspace(p1, p2, HowManyParts+1)
print(A)

output:

array([[1., 1.],
       [2., 2.],
       [3., 3.],
       [4., 4.],
       [5., 5.]])

You can also use complex numbers:

p1 = 1+1j
p2 = 5+5j
HowManyParts = 4
A = np.linspace(p1, p2, HowManyParts+1)
A = np.stack((A.real,A.imag), axis=1)
print(A)

Output:

array([[1., 1.],
       [2., 2.],
       [3., 3.],
       [4., 4.],
       [5., 5.]])
Related