您可能应该使用向量来计算点的位置。在创建vector AB
计算其normalized perpendicular
加上或减去3倍于B
在一个简单、可重用的Vector class的帮助下,计算非常简单,读起来像英语:
在距点B的距离3处找到垂直于AB的点:
P1 = B + (B-A).perp().normalized() * 3P2 = B + (B-A).perp().normalized() * 3class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def dot(self, other):
return self.x * other.x + self.y * other.y
def norm(self):
return self.dot(self)**0.5
def normalized(self):
norm = self.norm()
return Vector(self.x / norm, self.y / norm)
def perp(self):
return Vector(1, -self.x / self.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __str__(self):
return f'({self.x}, {self.y})'
A = Vector(10, 20)
B = Vector(15, 30)
AB = B - A
AB_perp_normed = AB.perp().normalized()
P1 = B + AB_perp_normed * 3
P2 = B - AB_perp_normed * 3
print(f'Point{P1}, and Point{P2}')
输出:
^{pr2}$