簡體   English   中英

使用內積計算兩個向量之間的角度

[英]Calculating the angle between two vectors using an inner product

我想創建一個函數來計算兩個向量x,y之間的角度,使用內部乘積的定義為x @ A @ y,其中A是一個正定矩陣。

我的功能如下:

def angle(A, x, y):

    import numpy as np
    from numpy.linalg import norm

    nominator = x@A@y
    denominator = (x@A@x)*(y@A@y)

    angle = np.arccos(nominator/denominator)

    return(angle)

但是,它沒有返回正確的答案。

例如,

y = np.array([0, -1])
x = np.array([1, 1])
A = np.array([
    [1, -1/2],
    [-1/2, 5]
])
angle(A, x, y)
1.7517827780414443

這不是正確的答案。

由於向量v的范數定義為sqrt(innerprod(v, v))需要采用分母的sqrt(innerprod(v, v)) 這會給您預期的答案嗎?

import numpy as np

def angle(A, x, y):
    nominator = x@A@y
    denominator = np.sqrt((x@A@x)*(y@A@y))
    angle = np.arccos(nominator/denominator)
    return(angle)

angle(A, x, y)
2.6905658417935308

暫無
暫無

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

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