2

I have a line with (x1,y1) and (x2,y2) endpoints. My task is to find my points in between. I want to find a point (xnew,ynew) from (x1,y1) such that xnew is 0.1 units distance from x1. How do I find ynew here?

My code:

# I know how to find the mid point
def find_line_mid(x1,y1,x2,y2)
    xnew = (x1+x2)/2
    ynew = (y1+y2)/2  
    return xnew,ynew
# My attempt
# We know that slope along the line is constant. We use it here
sl = (y2-y1)/(x2-x1)
xnew = x1+0.1
ynew = sl*(xnew)+y1 # from y=mx+c

is this a correct approach?

How can I find a point at a specific distance from the first point?

enter image description here

Georgy
  • 12,464
  • 7
  • 65
  • 73
Mainland
  • 4,110
  • 3
  • 25
  • 56
  • @ThierryLathuille I edited my q with my attempt. – Mainland Feb 10 '21 at 14:20
  • Related: [Find point-B on line by distance from point-A](https://stackoverflow.com/q/18843469/7851470), [Geometry: find point a specific distance between two points](https://stackoverflow.com/q/3411723/7851470). – Georgy Feb 10 '21 at 14:23
  • Draw a (large, it helps) figure, choose a simple slope (like 2), simple coordinates for your points, and draw the new point (you can start with xnew = x1 + 1 for a start, or x1+2), then see what the value of ynew is, and how it is related to the slope and so on. More generally, it is very often a good idea to draw and see what happens in simple cases before generalizing. – Thierry Lathuille Feb 10 '21 at 14:28
  • @ThierryLathuille Sure! I will try that. Thanks – Mainland Feb 10 '21 at 14:29

2 Answers2

2

If 3 points with resp. coordinates (x1, y1), (x2, y2) and (xnew, ynew) are aligned, and x1 != x2, then you have the following relation:

ynew - y1 == (xnew - x1) * (y2 - y1) / (x2 - x1)

It immediately gives:

ynew = y1 + (xnew - x1) * (y2 - y1) / (x2 - x1)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

Using Shapely, you could construct a vertical line at the specified distance from the given point (x1, y1), and find the intersection of both lines:

from shapely.geometry import LineString

x1, y1 = 0, 2
x2, y2 = 2, 0
x_dist = 0.5

line = LineString([(x1, y1), (x2, y2)])
x_new = x1 + x_dist
vertical = LineString([(x_new, y1), (x_new, y2)])
new_point = line.intersection(vertical)
print(new_point)
# POINT (0.5 1.5)
print(new_point.y)
# 1.5

enter image description here


Also, worth noting that Shapely actually provides interpolate method with similar functionality which is to find a point at the specified distance along a line:

line = LineString([(0, 0), (5, 5)])
distance = 2
new_point = line.interpolate(distance)
print(new_point)
# POINT (1.414213562373095 1.414213562373095)
Georgy
  • 12,464
  • 7
  • 65
  • 73