代码之家  ›  专栏  ›  技术社区  ›  ccc

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

  •  2
  • ccc  · 技术社区  · 8 年前

    我有两点 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)
    

    理论上,我需要将 XZ 和 YZ 到 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 回复  |  直到 8 年前
        1
  •  0
  •   AChampion    8 年前

    为了得到第三个顶点,你可以旋转这个点 (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)
    
        2
  •  1
  •   ewcz    8 年前

    要找到等边三角形的第三点并不需要任何复杂的东西,只需找到中间点即可 X 和 Y ,你知道这和点成直角 Z 所以只要映射到原点,乘以 sqrt(3) (等边三角形毕达哥拉斯理论的简化)并在两个方向上旋转90度( x,y => y,-x , x,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])
    
    推荐文章