Files
2026-04-21 11:24:43 +08:00

28 lines
925 B
Python
Raw Permalink 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
print("===== 题目3 向量运算 =====")
A = [3, 4]
B = [1, 2]
A_plus_B = [a + b for a, b in zip(A, B)]
print(f"A + B = {A_plus_B}")
two_A = [2 * a for a in A]
print(f"2 * A = {two_A}")
norm_A = math.sqrt(sum(x**2 for x in A))
print(f"A的模长 = {norm_A}")
print("\n===== 题目4 点积 & 余弦相似度 =====")
A1 = [1, 2, 3]
B1 = [4, 5, 6]
dot1 = sum(a*b for a, b in zip(A1, B1))
norm_A1 = math.sqrt(sum(x**2 for x in A1))
norm_B1 = math.sqrt(sum(x**2 for x in B1))
cos1 = dot1 / (norm_A1 * norm_B1)
print(f"A1·B1 点积 = {dot1}")
print(f"A1、B1 余弦相似度 = {cos1:.4f}")
A2 = [1, 0]
B2 = [0, 1]
dot2 = sum(a*b for a, b in zip(A2, B2))
norm_A2 = math.sqrt(sum(x**2 for x in A2))
norm_B2 = math.sqrt(sum(x**2 for x in B2))
cos2 = dot2 / (norm_A2 * norm_B2)
print(f"\nA2·B2 点积 = {dot2}")
print(f"A2、B2 余弦相似度 = {cos2}")
print("原因两向量正交夹角90°余弦值为0")