python 线段基础类

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)

线段基础类 含长度、斜率、截距、计算垂线交点、两线交点、判断点是否在线上

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值