Files
2026-04-21 11:29:52 +08:00

27 lines
735 B
Python

import math
# 向量 A, B
A = [1, 2, 3]
B = [4, 5, 6]
# ========== 1. 计算点积 ==========
dot = A[0]*B[0] + A[1]*B[1] + A[2]*B[2]
print("A · B =", dot)
# ========== 2. 计算余弦相似度 ==========
# 模长
norm_A = math.sqrt(A[0]**2 + A[1]**2 + A[2]**2)
norm_B = math.sqrt(B[0]**2 + B[1]**2 + B[2]**2)
# 余弦相似度
cos_sim = dot / (norm_A * norm_B)
print("余弦相似度 =", round(cos_sim, 4))
# ========== 3. A=[1,0], B=[0,1] 的余弦相似度 ==========
A2 = [1, 0]
B2 = [0, 1]
dot2 = A2[0]*B2[0] + A2[1]*B2[1]
norm_A2 = math.sqrt(A2[0]**2 + A2[1]**2)
norm_B2 = math.sqrt(B2[0]**2 + B2[1]**2)
cos_sim2 = dot2 / (norm_A2 * norm_B2)
print("\nA=[1,0], B=[0,1] 余弦相似度 =", cos_sim2)