Python 3.5.2:点到线的距离 [英] Python 3.5.2 : Distance from a point to a line

查看:231
本文介绍了Python 3.5.2:点到线的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

有人可以帮我写一个我想要的单独的函数或方法吗?我尝试了2个小时,但仍无法解决...

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 ...

推荐答案

您应该可以使用直接从这个点算起这个公式.因此,您将拥有类似的东西:

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

这篇关于Python 3.5.2:点到线的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆