Files
CalWay_Python/按方法整理/矩阵-模数-范数-点积.py
2025-06-19 09:34:40 +08:00

35 lines
1.3 KiB
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.

#模 范数
def Norm(x,v):
if len(x[0]) == 1:
if v == 1:
return sum([abs(i[0]) for i in x])
elif v == 2:
return (sum([i[0]**2 for i in x]))**0.5
elif v == float("inf"):
return max([abs(i[0]) for i in x])
else:
if v == 1:
return max([sum([abs(x[i][j]) for i in range(len(x))]) for j in range(len(x[0]))])
elif v == float("inf"):
return max([sum([abs(i) for i in x[j]]) for j in range(len(x))])
return None
# 计算矩阵的点积
def Dot(A,B):
if len(A[0]) != len(B):
return None
return [[sum([A[i][j] * B[j][k] for j in range(len(A[0]))]) for k in range(len(B[0]))] for i in range(len(A))]
#改成题干的矩阵##########################
if __name__ == "__main__":
A = [[1, 3], [-2, 4]] # 注意储存形式
x = [[1], [-1]] # 注意储存形式,单独一列的相量,每个数字都要中括号
print("Norm of x with v=1:", Norm(x, 1))
print("Norm of x with v=inf:", Norm(x, float("inf"))) # 1 1范数2 2范数float('inf') 无穷范数
print("Norm of x with v=2:", Norm(x, 2))
print("Dot product of A and x:", Dot(A, x))
print("Norm of Ax with v=2:", Norm(Dot(A, x), 2))
print("Norm of A with v=inf:", Norm(A, float("inf")))
print("Norm of A with v=1:", Norm(A, 1))