python3.x 中point类 && python实现点到直线的距离

使用的书本是python2.x ,在python3.x 中无法导入point类,只能加载下面point类,可以运行。
参考博客:https://blog.csdn.net/huoxingrenhdh/article/details/71708936

import math
class Point(object):
    def __init__(self,xParam = 0.0,yParam = 0.0):
        self.x = xParam
        self.y = yParam
 
    def __str__(self):
        return "(%.2f, %.2f)"% (self.x ,self.y)
 
    def distance (self,pt):
        xDiff = self.x - pt.x
        yDiff = self.y - pt.y
        return math.sqrt(xDiff ** 2 + yDiff ** 2)
 
    def sum(self,pt):
        newPt = Point()
        xNew = self.x + pt.x
        yNew = self.y + pt.y
        return Point(xNew,yNew)

以下是一个完整的点到直线的距离的代码:

#A Python program to calculate point to line distance
import math
def point2line(p,p1,p2):
    '''
    Calculate the distance from point to a line.
    Input
    p:the point
    p1 and p2:the two points that define a line
    Output
    d:distance from p to line p1p2
    '''
    x0=float(p.x)
    y0=float(p.y)
    x1=float(p1.x)
    y1=float(p1.y)
    x2=float(p2.x)
    y2=float(p2.y)
    dx=x1-x2
    dy=y1-y2
    a=dy
    b=-dx
    c=y1*dx-x1*dy
    if a==0 and b==0:#p1 and p2 are the same point
        d=math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0))
    else:
        d=abs(a*x0+b*y0+c)/math.sqrt(a*a+b*b)
    return d
class Point(object):
    def __init__(self,xParam = 0.0,yParam = 0.0):
        self.x = xParam
        self.y = yParam

    def __str__(self):
        return "(%.2f, %.2f)"% (self.x ,self.y)

    def distance (self,pt):
        xDiff = self.x - pt.x
        yDiff = self.y - pt.y
        return math.sqrt(xDiff ** 2 + yDiff ** 2)

    def sum(self,pt):
        newPt = Point()
        xNew = self.x + pt.x
        yNew = self.y + pt.y
        return Point(xNew,yNew)

if __name__=="__main__":
    p, p1, p2 = Point(10,0), Point(0,100), Point(0,1)
    print(point2line(p, p1, p2) )
    p, p1, p2 = Point(0,10), Point(1000,0.001), Point(-100,0)
    print(point2line(p, p1, p2) )
    p, p1, p2 = Point(0,0), Point(0,10), Point(10,0)
    print(point2line(p, p1, p2))
    p, p1, p2 = Point(0,0), Point(10,10), Point(10,10)
    print(point2line(p, p1, p2))
    

运行结果为:
10.0
9.999909090904959
7.071067811865475
14.142135623730951

你可能感兴趣的:(Python笔记)