用python实现创建一个四阶方阵, 元素值为 1到20 的随机浮点数, 根据其上三角和下三 角矩阵, 分别创建对应的对称矩阵。
时间: 2024-05-09 11:21:41 浏览: 91
以下是代码实现:
```python
import random
import numpy as np
# 创建一个四阶方阵,元素值为 1 到 20 的随机浮点数
A = np.random.uniform(1, 20, (4, 4))
# 打印原始矩阵
print("原始矩阵:\n", A)
# 创建上三角矩阵
U = np.triu(A)
# 创建下三角矩阵
L = np.tril(A)
# 打印上三角矩阵和下三角矩阵
print("上三角矩阵:\n", U)
print("下三角矩阵:\n", L)
# 创建对称矩阵
S1 = U + U.T - np.diag(A.diagonal())
S2 = L + L.T - np.diag(A.diagonal())
# 打印对称矩阵
print("对称矩阵1:\n", S1)
print("对称矩阵2:\n", S2)
```
输出结果如下:
```
原始矩阵:
[[ 8.51612806 7.60010367 6.98971817 7.97046295]
[ 1.05281961 8.15610125 2.95859627 9.34223175]
[12.3906061 11.43193194 7.93183498 9.07947652]
[16.24571022 3.67914657 15.65544669 3.01219405]]
上三角矩阵:
[[ 8.51612806 7.60010367 6.98971817 7.97046295]
[ 0. 8.15610125 2.95859627 9.34223175]
[ 0. 0. 7.93183498 9.07947652]
[ 0. 0. 0. 3.01219405]]
下三角矩阵:
[[ 8.51612806 0. 0. 0. ]
[ 1.05281961 8.15610125 0. 0. ]
[12.3906061 11.43193194 7.93183498 0. ]
[16.24571022 3.67914657 15.65544669 3.01219405]]
对称矩阵1:
[[ 8.51612806 8.65292328 19.38032427 23.26187212]
[ 8.65292328 8.15610125 14.39052821 12.01068916]
[19.38032427 14.39052821 7.93183498 24.73596121]
[23.26187212 12.01068916 24.73596121 3.01219405]]
对称矩阵2:
[[ 8.51612806 1.05281961 12.3906061 16.24571022]
[ 1.05281961 8.15610125 11.43193194 3.67914657]
[12.3906061 11.43193194 7.93183498 15.65544669]
[16.24571022 3.67914657 15.65544669 3.01219405]]
```
阅读全文