简体   繁体   English

使用内积计算两个向量之间的角度

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

I want to create a function to calculate the angle between two vectors x, y, using a definition of the Inner Product as x@A@y, where A is a positive-definite matrix. 我想创建一个函数来计算两个向量x,y之间的角度,使用内部乘积的定义为x @ A @ y,其中A是一个正定矩阵。

My function is the following: 我的功能如下:

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)

However, it does not return the right answer. 但是,它没有返回正确的答案。

Eg, 例如,

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

Which is not the right answer. 这不是正确的答案。

You need to take the square root of the denominator, since the norm of a vector v is defined as sqrt(innerprod(v, v)) . 由于向量v的范数定义为sqrt(innerprod(v, v))需要采用分母的sqrt(innerprod(v, v)) Does this give you the expected answer? 这会给您预期的答案吗?

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