Whud
Whud

Reputation: 714

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 !

Upvotes: 1

Views: 293

Answers (5)

Djaouad
Djaouad

Reputation: 22766

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

Upvotes: 2

Shiva Gupta
Shiva Gupta

Reputation: 402

print(abs(((y2-y1)*x0)-((x2-x1)*y0)+(x2*y1)-(y2*x1))/pow((y2-y1)**2+(x2-x1)**2),.5)

Upvotes: 0

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

A simple approach by breaking into multiple statement:

import math
x1,y1 = -1,0
x2,y2 = 1,0
x0,y0 = 0,1
p=(y2-y1)*x0
q=(x2-x1)*y0
r=(x2*y1)-(y2*x1)
d=math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
a=abs(p-q+r)
b=a/d
print (b)

Upvotes: 0

Leo Aso
Leo Aso

Reputation: 12463

This is correct and much cleaner

from math import sqrt

x1, y1 = -1, 0
x2, y2 =  1, 0
x0, y0 =  0, 1

dx = x2 - x1
dy = y2 - y1

dist = abs(dy*x0 - dx*y0 + x2*y1 - y2*x1) / sqrt(dy*dy + dx*dx)
print(dist)

Upvotes: 0

Deja
Deja

Reputation: 356

You are forgetting to evaluate the bottom section of the equation first before doing the division.

print(abs(((y2-y1)*x0)-((x2-x1)*y0)+(x2*y1)-(y2*x1))/((((y2-y1)**2)+((x2-x1)**2))**0.5))

demo

Upvotes: 0

Related Questions