Whud Whud - 26 days ago 7
Python Question

Distance from line to given point (given start and end points for line)

I am trying to write a function that returns the distance a point is from a line. I found this equation on wikipedia:

enter image description here

here is my example code:

x1,y1 = -1,0
x2,y2 = 1,0
x0,y0 = 0,1 #should be exactly 1 away from the line
print(abs(((y2-y1)*x0)-((x2-x1)*y0)+(x2*y1)-(y2*x1))/(((y2-y1)**2)+((x2-x1)**2))**1/2)


output:
0.25


expected:
1.0


I know I have more parentheses then I need in there but I've rewrote it 3 times trying to get this correct and wanted to make sure I wasn't getting order of operations wrong.

on a side question if anyone knows how to type longer equations like this in python without them getting so messy I'm all ears.

Thanks for any help !

Answer Source

When you write x**1/2, you're raising x to the power of 1 (which is just x), then dividing the result by 2 (so x**1/2 == x/2), to avoid this, either use parentheses, .5 or (better) use math.sqrt(x):

print(abs(((y2-y1)*x0)-((x2-x1)*y0)+(x2*y1)-(y2*x1))/(((y2-y1)**2)+((x2-x1)**2))**(1/2))
# => 1.0
print(abs(((y2-y1)*x0)-((x2-x1)*y0)+(x2*y1)-(y2*x1))/(((y2-y1)**2)+((x2-x1)**2))**.5)
# => 1.0
# Or
from math import sqrt
print(abs(((y2-y1)*x0)-((x2-x1)*y0)+(x2*y1)-(y2*x1))/sqrt(((y2-y1)**2)+((x2-x1)**2)))
# => 1.0

Also, to avoid long expressions like this, separate them by assigning a function to each:

def pDistp(x1, y1, x2, y2):
    return (((y2-y1)**2)+((x2-x1)**2))**.5
def numerator(x0, y0, x1, y1, x2, y2):
    return abs(((y2-y1)*x0)-((x2-x1)*y0)+(x2*y1)-(y2*x1))

x1,y1 = -1,0
x2,y2 = 1,0
x0,y0 = 0,1
print(numerator(x0, y0, x1, y1, x2, y2) / pDistp(x1, y1, x2, y2))
# => 1.0