user8270077
user8270077

Reputation: 5071

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.

E.g.,

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.

Upvotes: 0

Views: 998

Answers (1)

Peter Leimbigler
Peter Leimbigler

Reputation: 11105

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

Upvotes: 1

Related Questions