完成作业X
This commit is contained in:
23
test3.py
Normal file
23
test3.py
Normal file
@@ -0,0 +1,23 @@
|
||||
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。")
|
||||
Reference in New Issue
Block a user