简体   繁体   中英

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.

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)) . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM