为平面中的给定两点创建等边三角形 - Python

Creating an equilateral triangle for given two points in the plane - Python

我在笛卡尔平面上有两个点 X = (x1,y1)Y=(x2,y2)。我需要找到第三个点 Z = (x,y) 使得这三个点构成一个等边三角形。

我正在使用以下代码示例计算两点之间的欧氏距离:

def distance(points, i, j):
dx = points[i][0] - points[j][0]
dy = points[i][1] - points[j][1]
return math.sqrt(dx*dx + dy*dy)

理论上,我需要使XZYZ的距离等于XY。这给了我们两个可能的答案,我也需要它们。但是我很难在我的代码中启动 Z 点。有人可以帮我吗? 以下是我尝试过的示例。

L = [0, 6]  #known two points
d= distance(points, L[0], L[1])
x = Symbol('x')
y = Symbol('y')
newpoint = x,y   #coordintes of the third point of the triangle
f1 = distance(points, L[0], newpoint)
f2 = distance(points, L[1], newpoint)
print(nsolve((f1, f2), (x, y), (d,d)))

但是这个returns出现以下错误:

 File "/Users/*.py", line 99, in <module>
    f1 = distance(points, L[0], newpoint)

  File "/Users/*.py", line 36, in distance
    dx = points[i][0] - points[j][0]

TypeError: list indices must be integers or slices, not tuple

为了获得第三个顶点,您可以将点 (x2, y2) 围绕点 (x1, y1) 旋转 60 度。另一个可接受的解决方案将通过旋转 -60 度获得,即在相反的方向上。

import math


def get_point(x1, y1, x2, y2):
    #express coordinates of the point (x2, y2) with respect to point (x1, y1)
    dx = x2 - x1
    dy = y2 - y1

    alpha = 60./180*math.pi
    #rotate the displacement vector and add the result back to the original point
    xp = x1 + math.cos( alpha)*dx + math.sin(alpha)*dy
    yp = y1 + math.sin(-alpha)*dx + math.cos(alpha)*dy

    return (xp, yp)


print(get_point(1, 1, 2, 1))
# (1.5, 0.1339745962155614)

求等边三角形的第三点并不需要什么很复杂的东西,只要找到XY之间的中点,就知道这是一个直角点Z所以只要映射到原点,乘以sqrt(3)(等边三角形的毕达哥拉斯理论的简化)并在两个方向上旋转90度(x,y => y,-xx,y => -y,x),并映射回来,例如:

X, Y = (1,1), (2,1)
M = (X[0]+Y[0])/2, (X[1]+Y[1])/2            # Mid point
O = (X[0]-M[0])*3**0.5, (X[1]-M[1])*3**0.5  # Map to origin, multiply sqrt(3)

In []:
M[0]+O[1], M[1]-O[0]                        # Rotate 90 (y,-x), map back

Out[]:
(1.5, 1.8660254037844386)

In []:
M[0]-O[1], M[1]+O[0]                        # Rotate -90 (-y,x), map back

Out[]:
(1.5, 0.1339745962155614)

你可以在 numpy 中做到这一点:

X, Y = np.array([1,1]), np.array([2,1])
M = (X + Y) / 2
O = (X - M) * 3**0.5
t = np.array([[0, -1], [1, 0]])   # 90 degree transformation matrix

In []:
M + O @ t

Out[]:
array([1.5      , 1.8660254])

In []:
M + O @ t.T                       # the transpose gives -90

Out[]:
array([1.5      , 0.1339746])