pythongeometryshapely

Draw perpendicular line of fixed length at a point of another line


I have two points A (10,20) and B (15,30). The points generate a line AB. I need to draw a perpendicular line, CD, on point B with a length of 6 (each direction 3 units) in Python.

I already have some properties of line AB using the following code:

from scipy import stats
x = [10,15]
y = [20,30]
slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)

How can I calculate the location of C and D. I need their X and Y value. enter image description here

The value of C and D will be used for accomplishing another objective using the Shapely library.


Solution

  • If slope is the slope of AB, then the slope of CD is -1/slope. This is equal to vertical change over horizontal change: dy/dx = -1/slope. This gives that dx = -slope*dx. And by Pythagorean Theorem, you have 3**2 = dy**2+dx**2. Substitute for dx, and you get

    3**2 = (-slope*dy)**2+dy**2
    3**2 = (slope**2 + 1)*dy**2
    dy**2 = 3**2/(slope**2+1)
    dy = math.sqrt(3**2/(slope**2+1))

    Then you can get dx = -slope*dy. Finally, you can use dx and dy to get C and D. So the code would be:

    import math
    dy = math.sqrt(3**2/(slope**2+1))
    dx = -slope*dy
    C[0] = B[0] + dx
    C[1] = B[1] + dy
    D[0] = B[0] - dx
    D[1] = B[1] - dy
    

    (Note that although math.sqrt returns only one number, in general there is a positive and negative square root. C corresponds to the positive square root, and D to the negative).