1
$\begingroup$

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 "Your vector is null."
    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.

$\endgroup$
8
  • 1
    $\begingroup$ 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) $\endgroup$ Feb 10, 2020 at 16:14
  • 1
    $\begingroup$ StackOverflow has a NumPy tag. Your question is much more appropriate there. $\endgroup$ Feb 10, 2020 at 16:14
  • 1
    $\begingroup$ @IzaakvanDongen Oh yes of course, interestingly I didn't think about it here even though I use vectorized functions all the time :) $\endgroup$ Feb 10, 2020 at 16:19
  • 1
    $\begingroup$ 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. $\endgroup$ Feb 10, 2020 at 16:20
  • 1
    $\begingroup$ 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. $\endgroup$ Feb 10, 2020 at 16:26

0

You must log in to answer this question.

Browse other questions tagged .