Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equidistant points between two points?

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.

like image 597
mikesneider Avatar asked Nov 22 '17 20:11

mikesneider


2 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)]
like image 64
randomir Avatar answered Sep 25 '22 13:09

randomir


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)]
like image 26
Joe Iddon Avatar answered Sep 22 '22 13:09

Joe Iddon