Python 3.5.2:点到lin的距离

2024-06-01 00:09:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个类“点”,我想计算一个给定点和一条直线之间的最短距离(由另外两个点表示),所有点都是已知的。 我试着用这个公式:| Ax+By+C |/sqrt(A^2+B^2),但我搞砸了,被时间弄糊涂了(主要是因为数学公式:)。。。

我确实找到了一些网站,人们也问了这个问题,但它要么不是为Python,要么是在一个三维系统,而不是二维。。。


下面是我的课:

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

有人能帮我写一个独立的函数或方法来做我想要的吗?我试了两个小时都没想出来。。。


Tags: theselfreturndef直线定点pointother
2条回答

两点之间的距离公式是Distance =sqrt((x2−x1)^2+(y2−y1)^2)。 计算斜率的公式是slope = (y2 - y1) / (x2 - x1)

下面是一个简单的计算距离的方法

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

在第二种方法slope中,我乘以1.0,结果将是浮动的。 注意-我使用了Python2.7.6的语法,不过希望它也能在Python3.x中工作。

您应该能够直接从点使用this公式。所以,你会得到这样的东西:

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

相关问题 更多 >