Whud Whud - 5 months ago 36
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



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):

# => 1.0
# => 1.0
# Or
from math import sqrt
# => 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download