Files
task-3-2-1-Text-Processing-…/test3.py
2026-04-21 11:24:07 +08:00

23 lines
747 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import math
A = [1, 2, 3]
B = [4, 5, 6]
def dot_product(v1, v2):
return sum(x * y for x, y in zip(v1, v2))
A_dot_B = dot_product(A, B)
print("1. A · B =", A_dot_B)
def vector_norm(v):
return math.sqrt(sum(x ** 2 for x in v))
def cosine_similarity(v1, v2):
dot = dot_product(v1, v2)
norm1 = vector_norm(v1)
norm2 = vector_norm(v2)
if norm1 == 0 or norm2 == 0:
return 0.0
return dot / (norm1 * norm2)
cos_sim = cosine_similarity(A, B)
print("2. 余弦相似度 =", round(cos_sim, 4))
A2 = [1, 0]
B2 = [0, 1]
cos_sim2 = cosine_similarity(A2, B2)
print("3. A=[1,0], B=[0,1] 的余弦相似度 =", cos_sim2)
print(" 原因:点积为 0说明两向量正交夹角为 90°所以余弦相似度为 0。")