# Why does my NumPy function not work out the cosine of two vectors?

I have this function to work out the cosine between two vectors, except it isn't working for some reason.

def length(x):
return math.sqrt(x.dot(x))

def unitVectorNormalize(u):
if length(u) == 0:
return u / length(u)

def cosine(vector1, vector2):
return vector1.dot(vector2) / (unitVectorNormalize(vector1) * unitVectorNormalize(vector2))


Is there something I am doing wrong?

I am aware that there is a NumPy method to figure out the cosine similarity, but I am told (for my course) to write my own fucntion.

• The formula is $\cos \theta = \mathbf a \cdot \mathbf b / (\lvert \mathbf a \rvert \lvert \mathbf b \rvert)$, which is not what you've implemented - the denominator should be length(vector1) * length(vector2) Feb 10, 2020 at 16:14
• StackOverflow has a NumPy tag. Your question is much more appropriate there. Feb 10, 2020 at 16:14
• @IzaakvanDongen Oh yes of course, interestingly I didn't think about it here even though I use vectorized functions all the time :) Feb 10, 2020 at 16:19
• Wow, I feel silly. Maths isn't something I do much of, but I have to do it for my CS course. I thought the formula showed that the it was to be divided by the unit vectors of a and b. Feb 10, 2020 at 16:20
• Not to worry :) We all have these moments. Just be clear on the notation - $\lvert \mathbf a \rvert$ is always a length, unit vectors are sometimes written $\hat{\mathbf a}$. (unrelated tip - I'd use raise ValueError("Cannot normalise null vector") or something along those lines. Feb 10, 2020 at 16:26