Issue
I want to calculate the angle between vectors. I thought the sum of 2 vectors should be in the middle of the 2. But calculating the angle with my method gives different results. I guess it has to be with rounding but the result is too different. I tried 2 different approaches. Can you explain me, why? Or am I wrong with my math understanding?
from numpy import (array, dot, arccos, clip, sum)
from numpy.linalg import norm
import spectral
import numpy as np
def calculateAngle(u, v):
c = dot(u, v) / norm(u) / norm(v) # -> cosine of the angle
angle = arccos(clip(c, -1, 1)) # if you really want the angle
return c, angle
def calc_with_numpy():
print("Method 2:")
v = (u1_norm + u2_norm)
c1, angle1 = calculateAngle(u1, v)
c2, angle2 = calculateAngle(u2, v)
print("angle1:", angle1)
print("angle2:", angle2)
def calc_with_spectral():
print("Method 1:")
v = (u1_norm + u2_norm)
img=np.array([v]).reshape((1,1,v.size))
means = np.array([u1, u2])
angles = spectral.spectral_angles(img, means)
print("angle1:", angles[0,0,0])
print("angle2:", angles[0, 0, 1])
u1 = array([1.0,2.0], dtype="float64")
u1_norm = u1 / sum(u1)
u2 = array([3.0,2.0], dtype="float64")
u2_norm = u2 / sum(u2)
calc_with_spectral()
calc_with_numpy()
My results:
Method 1:
angle1: 0.25518239062081866
angle2: 0.2639637236257044
Method 2:
angle1: 0.2551823906208191
angle2: 0.2639637236257044
Solution
You are wrong here
u1_norm = u1 / sum(u1)
u2_norm = u2 / sum(u2)
To get normalized (unit length) vector, you need to divide it's components by vector length, not by component sum (like you perform right job inside calculateAngle
)
u1_norm = u1 / np.linalg.norm(u1)
Answered By - MBo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.