How to calculate the coordinates of the line between two points in python?

19,315

Solution 1

"All of them"? There are an infinite number.

You can calculate the slope and intercept of the line between those two points. Knowing those you can calculate the value for y at every value of x you wish using the equation for the line.

This is high school algebra. What's the problem?

Given two points (x1, y1) and (x2, y2) the equation for the line between them is:

y = m*x + b

where

m = slope = (y1-y2)/(x1-x2)

and

b = y-intercept = (x1*y2 - x2*y1)/(x1-x2)

If you mean "draw the circle passing between the two points and find all the points inside", I'd calculate the center point as the midpoint of that line and radius equal to half the length of that line. You calculate whether or not a point is inside or outside the circle by determining the distance from the center and comparing it to the radius.

There are an infinite numbers of points both inside and outside the circle. What are you really trying to do here?

Solution 2

Seems you want to generate a list of integer points for the line segment between given points. This problem is solved in computer graphics, for example, using Bresenham algorithm or DDA algo

Solution 3

def intermediates(p1, p2, nb_points=8):
    """"Return a list of nb_points equally spaced points
    between p1 and p2"""
    # If we have 8 intermediate points, we have 8+1=9 spaces
    # between p1 and p2
    x_spacing = (p2[0] - p1[0]) / (nb_points + 1)
    y_spacing = (p2[1] - p1[1]) / (nb_points + 1)

    return [[p1[0] + i * x_spacing, p1[1] +  i * y_spacing] 
            for i in range(1, nb_points+1)]

print(intermediates([1, 2], [10, 6.5], nb_points=8))

# [[2.0, 2.5], [3.0, 3.0], [4.0, 3.5], [5.0, 4.0], 
#  [6.0, 4.5], [7.0, 5.0], [8.0, 5.5], [9.0, 6.0]]
Share:
19,315
Karak
Author by

Karak

Updated on July 28, 2022

Comments

  • Karak
    Karak almost 2 years

    How can I get all the coordinate points between two points in python? For example: I have a point with the coordinates of x1, y1 and an other with x10, y10. I need all the points between them (in this case for instance x2, y2 ... x9, y9). Huge thanks for your help!

  • jrd1
    jrd1 about 7 years
    I think the OP is referring to finding points within a radius defined by the distance between 2 points (i.e. from the fact that he mentioned x1, and x10 - implying that there are at most 8 other points in-between).
  • duffymo
    duffymo about 7 years
    I can't tell which one the OP means. I gave the solution for both. If the down vote is yours, I'd recommend removing it. Both of my solutions are correct.
  • jrd1
    jrd1 about 7 years
    Agreed, and likewise! I think your response answered both accurately. Hopefully he is able to clarify that soon. The downvote wasn't mine, but the last upvote was (pushing it to +2/-1 from +1/-1).
  • angerhang
    angerhang almost 5 years
    There is a typo in the b definition it should be x1*y2 - x2*y1.