35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
#模 范数
|
|
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")))
|
|
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))
|
|
|
|
|