Python 3.5.2 : Distance from a point to a line

左心房为你撑大大i 提交于 2020-01-11 04:14:07

问题


I have created a class "Point" and i want to calculate the shortest distance between a given point and a line ( characterized by 2 other points ), all points are known. I tried to use this formula : |Ax+By+C| / sqrt(A^2+B^2) , but i messed up and got more confused by the minute (mostly because of math formulas :( )...

I did find some sites where people asked this question too, but it either was not for Python or it was in a 3D system not 2D ...

​​
Below is my class :

class Point:
        def __init__(self,initx,inity):
            self.x = initx
            self.y = inity
        def getX(self):
            return self.x
        def getY(self):
            return self.y
        def __str__(self):
            return "x=" + str(self.x) + ", y=" + str(self.y)
        def distance_from_point(self,the_other_point):
            dx = the_other_point.getX() - self.x
            dy = the_other_point.getY() - self.y
        def slope(self,other_point):
            if self.x - other_point.getX() == 0 :
                return 0
            else:
                panta = (self.y - other_point.getY())/ (self.x - other_point.getX())
                return panta

Can someone help me write a separate function or a method that does what i want ? I tried for 2 hours and I can't figure it out ...


回答1:


You should be able to use this formula from the points directly. So, you'd have something like:

import math

class Point:
    def distance_to_line(self, p1, p2):
        x_diff = p2.x - p1.x
        y_diff = p2.y - p1.y
        num = abs(y_diff*self.x - x_diff*self.y + p2.x*p1.y - p2.y*p1.x)
        den = math.sqrt(y_diff**2 + x_diff**2)
        return num / den



回答2:


The distance formula between two points is Distance =sqrt((x2−x1)^2+(y2−y1)^2). And the formula to calculate slope is slope = (y2 - y1) / (x2 - x1).

so below is a simple method to calculate the distance

def distance_from_other_point(self, other_point):
    return math.sqrt( ( other_point.getX() - self.getX() )**2 + ( other_point.getY() - self.getY() )**2 )

def slope(self, otehr_point):
   return ( other_point.getY() - self.getY() )*1.0 / ( other_point.getX() - self.getX() )

In the second method, slope, I multiplied with 1.0 so that result will be in float. Note - I used the syntax of python 2.7.6 though hopefully, it will work in python 3.x as well.



来源:https://stackoverflow.com/questions/40970478/python-3-5-2-distance-from-a-point-to-a-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!