编写程序实现: 1、输于两个n×n的矩阵A和B,实现乘积运算,并输出运算结果和计算时间; 2、逐渐增大矩阵A和B的规模,分析运算时间的变化。 3、用分治法的实现矩阵乘积运算,比较使用分治法前后的计算量差异。
时间: 2024-04-30 14:18:23 浏览: 88
n 模张量 - 矩阵乘积:计算张量和矩阵之间的 n 模乘积。-matlab开发
5星 · 资源好评率100%
以下是 Python 代码实现:
1. 普通矩阵乘积运算
```python
import numpy as np
import time
# 生成随机矩阵
n = 1000
A = np.random.rand(n, n)
B = np.random.rand(n, n)
# 计时开始
start_time = time.time()
# 矩阵乘积运算
C = np.dot(A, B)
# 计时结束
end_time = time.time()
# 输出结果和时间
print("矩阵乘积运算结果:\n", C)
print("计算时间:", end_time - start_time, "秒")
```
2. 规模逐渐增大的矩阵乘积运算
```python
import numpy as np
import time
for n in range(1000, 4001, 1000):
# 生成随机矩阵
A = np.random.rand(n, n)
B = np.random.rand(n, n)
# 计时开始
start_time = time.time()
# 矩阵乘积运算
C = np.dot(A, B)
# 计时结束
end_time = time.time()
# 输出结果和时间
print("矩阵规模:", n)
print("计算时间:", end_time - start_time, "秒")
```
3. 分治法实现矩阵乘积运算
```python
import numpy as np
import time
def matrix_multiply(A, B):
n = len(A)
# 边界条件
if n == 1:
return [[A[0][0] * B[0][0]]]
else:
# 分治递归
A11 = [row[:n//2] for row in A[:n//2]]
A12 = [row[n//2:] for row in A[:n//2]]
A21 = [row[:n//2] for row in A[n//2:]]
A22 = [row[n//2:] for row in A[n//2:]]
B11 = [row[:n//2] for row in B[:n//2]]
B12 = [row[n//2:] for row in B[:n//2]]
B21 = [row[:n//2] for row in B[n//2:]]
B22 = [row[n//2:] for row in B[n//2:]]
C11 = np.add(matrix_multiply(A11, B11), matrix_multiply(A12, B21))
C12 = np.add(matrix_multiply(A11, B12), matrix_multiply(A12, B22))
C21 = np.add(matrix_multiply(A21, B11), matrix_multiply(A22, B21))
C22 = np.add(matrix_multiply(A21, B12), matrix_multiply(A22, B22))
# 合并结果
C = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n//2):
for j in range(n//2):
C[i][j] = C11[i][j]
C[i][j+n//2] = C12[i][j]
C[i+n//2][j] = C21[i][j]
C[i+n//2][j+n//2] = C22[i][j]
return C
# 生成随机矩阵
n = 8
A = np.random.rand(n, n)
B = np.random.rand(n, n)
# 计时开始
start_time = time.time()
# 分治法矩阵乘积运算
C = matrix_multiply(A, B)
# 计时结束
end_time = time.time()
# 输出结果和时间
print("矩阵乘积运算结果:\n", C)
print("计算时间:", end_time - start_time, "秒")
```
通过比较普通矩阵乘积运算和分治法矩阵乘积运算的计算时间,可以发现当矩阵规模较大时,分治法可以显著减少计算时间。
阅读全文