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

时间:2018-05-26 21:17:48

标签: python-3.x euclidean-distance

我在笛卡尔平面上有两个点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)))

但是这会返回以下错误:

 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

2 个答案:

答案 0 :(得分:1)

为了获得第三个顶点,您可以围绕点(x2, y2)将点60旋转(x1, y1)度。另一个可接受的解决方案是旋转-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)

答案 1 :(得分:0)

要找到等边三角形的第三个点并不需要任何真正复杂的东西,只需找到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])