import math
class Point:
x: float
y: float
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def to_str(self) -> str:
return "Point(" + ("None" if self.x is None else format(self.x, ".4f")) + ',' + ("None" if self.y is None else format(self.y, ".4f")) + ')'
def distance(a: Point, b: Point) -> float:
return math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)
class Line:
A: Point
B: Point
k: float
C: float
def __init__(self, pointA: Point, pointB: Point):
self.A = pointA
self.B = pointB
self.k = self.slope()
self.C = self.C()
def to_str(self) -> str:
return "Line=" + str(self.k) + "x + " + str(self.C)
def length(self) -> float:
return distance(self.A, self.B)
def slope(self):
if self.A.x == self.B.x:
return None
return (self.A.y - self.B.y) / (self.A.x - self.B.x)
def C(self):
if self.A.x == self.B.x:
return None
return self.B.y - self.k * self.B.x
def footPoint(self, a: Point) -> Point:
if self.A.x == self.B.x:
return Point(self.A.x, a.y)
if self.A.y == self.B.y:
return Point(a.x, self.A.y)
targetX = ((a.y-self.C)*self.k+a.x)/(1+self.k)
targetY = targetX * self.k + self.C
return Point(targetX, targetY)
def inline(self, p: Point) -> bool:
if p is None:
return False
if p.x > max(self.A.x, self.B.x) or p.x < min(self.A.x, self.B.x) or p.y > max(self.A.y, self.B.y) or p.y < min(self.A.y, self.B.y):
return False
return p.y == p.x * self.k + self.C
def crossPoint(a: Line, b: Line):
if (a.A.x == a.B.x and b.A.x == b.B.x) or a.k == b.k:
return None
if a.A.x == a.B.x:
return Point(a.A.x, a.A.x * b.k + b.C)
if b.A.x == b.B.x:
return Point(b.A.x, b.A.x * a.k + a.C)
targetX = (b.C - a.C) / (a.k - b.k)
targetY = a.k * targetX + a.C
return Point(targetX, targetY)
线段基础类 含长度、斜率、截距、计算垂线交点、两线交点、判断点是否在线上