Python 3.5.2:点到线的距离

ROB*_*ail 0 python point distance line python-3.x

我创建了一个“点”类,我想计算给定点和线(以其他 2 个点为特征)之间的最短距离,所有点都是已知的。我尝试使用这个公式:|Ax+By+C| / sqrt(A^2+B^2) ,但我搞砸了,一分钟后变得更加困惑(主要是因为数学公式:()...

我确实找到了一些人们也问这个问题的网站,但它要么不是针对 Python 的,要么是在 3D 系统中而不是 2D ...

??
下面是我的课:

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
Run Code Online (Sandbox Code Playgroud)

有人可以帮我写一个单独的函数或方法来做我想要的吗?我试了2个小时,我无法弄清楚......

Ilu*_*tar 5

您应该能够直接从点使用公式。所以,你会有类似的东西:

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
Run Code Online (Sandbox Code Playgroud)