pythonlinepoints

finding points that reside on a line between 2 points, in accurate segments, python


I have 2 points, (x0,y0) (x1,y1) which form a line L. I found the slope M. Now I want to find 3 points between these 2 points that reside on L, that is between them in an accurate distance, meaning same distance between all points. If I measure the distance with the "-" char, it can be something like: p1---p2---p3---p4---p5 where p1 and p5 are my starting points.

First I thought about finding the slope by doing something like this:

def findSlope(p1, p2):
if (p1[0] - p2[0] != 0):
    return (p1[1] - p2[1])/p1[0] - p2[0]
else:
    return 0

This is pretty easy, but getting the actual points is not coming easy to me. I thought about doing something like this:

def findThreePoints(p1,p2):

    slope = findSlope(p1,p2)
    c = p1[1] - slope*p1[0]
    x1 = (p1[0] + p2[0])/4
    x2 = (p1[0] + p2[0])/2
    x3 = (3*(p1[0] + p2[0]))/4
    y1 = slope*x1 + c
    y2 = slope*x2 + c
    y3 = slope*x3 + c

While this approach works, it is not very nice coding style/efficiency, since if I want the function to give more than 3 points, I will need it to be much longer.

Is there any built in way to do this with Numpy, or just a more efficient approach to the matter, that does not make my code look like it was written for only a certain purpose?


Solution

  • As simple as it gets:

    import numpy as np
    
    #create the points 
    number_of_points=3
    xs=np.linspace(x0,x1,number_of_points+2)
    ys=np.linspace(y0,y1,number_of_points+2)
    
    #print them
    for i in range(len(xs)):
        print (xs[i],ys[i])
    

    And it also works for horizontal or vertical lines