完成作业3-2-1
This commit is contained in:
@@ -0,0 +1,16 @@
|
|||||||
|
import math
|
||||||
|
|
||||||
|
A = [3, 4]
|
||||||
|
B = [1, 2]
|
||||||
|
|
||||||
|
# 1. A + B
|
||||||
|
add_result = [a + b for a, b in zip(A, B)]
|
||||||
|
print("A + B =", add_result)
|
||||||
|
|
||||||
|
# 2. 2 × A
|
||||||
|
scalar_result = [2 * a for a in A]
|
||||||
|
print("2 × A =", scalar_result)
|
||||||
|
|
||||||
|
# 3. A的长度
|
||||||
|
norm = math.sqrt(sum(a**2 for a in A))
|
||||||
|
print("A的长度 =", norm)
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import math
|
||||||
|
|
||||||
|
def cosine_similarity(a, b):
|
||||||
|
dot = sum(x * y for x, y in zip(a, b))
|
||||||
|
norm_a = math.sqrt(sum(x**2 for x in a))
|
||||||
|
norm_b = math.sqrt(sum(x**2 for x in b))
|
||||||
|
return dot / (norm_a * norm_b)
|
||||||
|
|
||||||
|
# 题目4-1,4-2
|
||||||
|
A = [1, 2, 3]
|
||||||
|
B = [4, 5, 6]
|
||||||
|
dot_product = sum(a*b for a,b in zip(A,B))
|
||||||
|
print("点积 =", dot_product)
|
||||||
|
print("余弦相似度 =", cosine_similarity(A, B))
|
||||||
|
|
||||||
|
# 题目4-3
|
||||||
|
A2 = [1, 0]
|
||||||
|
B2 = [0, 1]
|
||||||
|
print("特殊向量余弦相似度 =", cosine_similarity(A2, B2))
|
||||||
Reference in New Issue
Block a user