Home > Back-end >  To which quarter of the line segment does a given point belong?
To which quarter of the line segment does a given point belong?

Time:05-31

If we divide a line segment (with clear source and destination points) to some (equal) parts e.g. 4 quarters, how can we efficiently determine to which quarter a given point belongs?

For example, given a line segment passes from (0, 0) to the (0, 4). Dividing the line segment into the 4 parts, the point (0, 0.5) belongs to the quarter 1.

How will be the code for such a determination in Python?

CodePudding user response:

Let the segment be from A to B. Compute vectorially

t = AP.AB / AB²

This gives you a reduced abscissa along AB (0 at A, 1 at B, <0 or >1 outside the segment).

CodePudding user response:

Line segment start coordinate: a1 = (x1, y1)

Line segment end coordinate: a2 = (x2, y2)

Given point: z = (x3, y3)

Number of parts: n = 4

line_seg_length = ((x1 - x2)**2   (y1 - y2)**2)**0.5
start_to_point_len = ((x1 - x3)**2   (y1 - y3)**2)**0.5
part = int(start_to_point_len / line_seg_length * n)   1

The result will be a value between 1 to 4 as the quarter number of the line segment to which the give point belongs.

I appreciate it to see a more efficient solution/code.

  • Related