簡體   English   中英

根據隨機點求兩條相連線段的角度

[英]Find the angle of two connected line segments based upon a random point

我有 3 對 x、y 坐標(A、B、C),它們形成兩個連接的線段。

在此處輸入圖片說明

我想根據可以落在線段任一側的隨機點(x,y 坐標)計算線段的角度。

例如,如果隨機點是 D,我想計算綠色角度,或者如果隨機點是 E,我想計算紅色角度。

這是我要完成的函數簽名:

function angle(segment_1, segment_2, random_point) {

}

在你的函數中,你可以在你的隨機點和基地之間創建一個中間段,然后添加這兩個角度

angle(BA,BE) + angle(BE,BC);

您需要一些基本功能,如標量積和叉積來實現這一點;

import math
from collections import namedtuple
Point = namedtuple('Point', 'x y')

# define nom of a vector
def norm(v):
    n = math.sqrt(v.x*v.x + v.y*v.y)
    return n

# normalise a vector
def normedVec(v):
    n = norm(v)
    nv = Point(v.x/n, v.y/n)
    return nv

# print angle in degrees
def printAngle(name,rad):
    deg = rad * 180.0 / math.pi
    print("{}={}".format(name,deg))

# scalar (aka dot)product of 2 vectors 
def dotProduct(v1,v2):
    d = v1.x*v2.x +  v1.y*v2.y
    print("dot={}".format(d))
    return d

# vectorial (aka cross) product
def crossProd(v1,v2):
    c = v1.x*v2.y - v1.y*v2.x
    print("c={}".format(c))
    return c

# compute angle between 2 vectoris
def angle(s1,s2):
    n1 = normedVec(s1)
    n2 = normedVec(s2)
    cosAngle = dotProduct(n1,n2)
    d = crossProd(n1,n2)
    angle = math.acos(cosAngle)
    if d <= 0:
        angle = - angle
    printAngle("angle",angle)
    return angle

# compute angle between 2 vectors using point orientation 
def angleOriented(AB,AC,AX):
    # Compute angle between 2 vectors
    ABC = angle(AB, AC)
    # Compute angle to random point
    ABX = angle(AB, AX)
    # if angle is negative then change angle sign 
    if ABX < 0:
        ABC = - ABC
    # put angle between 0 and 360
    while ABC < 0:
        ABC += 2*math.pi
    printAngle("Oriented",ABC)

# test
AB = Point(1,0)
AC = Point(-1,1)
AD = Point(0,-1)
AE = Point(0,1)

ABE = angleOriented(AB,AC,AE)
print("-----")
ABD = angleOriented(AB,AC,AD)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM