Ex1t's space

使用numpy解方程组

字数统计: 466阅读时长: 2 min
2017/04/03 Share

使用numpy解方程组

先放出代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from numpy import mat, matrix
a = mat(
[
[0x4D, 0x79, 0x64, 0x65, 0x61, 0x72, 0x66, 0x6F,
0x72, 0x74, 0x68, 0x65, 0x68, 0x75, 0x72, 0x74],
[0x49, 0x63, 0x61, 0x6E, 0x6E, 0x6F, 0x74, 0x63,
0x68, 0x6F, 0x6F, 0x73, 0x65, 0x74, 0x68, 0x65],
[0x4D, 0x79, 0x77, 0x69, 0x73, 0x68, 0x65, 0x73,
0x61, 0x72, 0x65, 0x66, 0x6F, 0x6F, 0x6C, 0x73],
[0x57, 0x68, 0x61, 0x74, 0x79, 0x6F, 0x75, 0x61,
0x72, 0x65, 0x79, 0x6F, 0x75, 0x64, 0x6F, 0x6E],
[0x44, 0x6F, 0x6E, 0x6F, 0x74, 0x73, 0x65, 0x61,
0x74, 0x79, 0x6F, 0x75, 0x72, 0x6C, 0x6F, 0x76],
[0x44, 0x65, 0x6C, 0x75, 0x73, 0x69, 0x6F, 0x6E,
0x73, 0x6F, 0x66, 0x6B, 0x6E, 0x6F, 0x77, 0x6C],
[0x4C, 0x69, 0x73, 0x74, 0x65, 0x6E, 0x6D, 0x79,
0x68, 0x65, 0x61, 0x72, 0x74, 0x74, 0x6F, 0x74],
[0x53, 0x6F, 0x6D, 0x65, 0x75, 0x6E, 0x73, 0x65,
0x65, 0x6E, 0x66, 0x69, 0x6E, 0x67, 0x65, 0x72],
[0x53, 0x6F, 0x72, 0x72, 0x6F, 0x77, 0x69, 0x73,
0x68, 0x75, 0x73, 0x68, 0x65, 0x64, 0x69, 0x6E],
[0x4F, 0x6E, 0x63, 0x65, 0x77, 0x65, 0x64, 0x72,
0x65, 0x61, 0x6D, 0x74, 0x74, 0x68, 0x61, 0x74],
[0x48, 0x65, 0x72, 0x77, 0x69, 0x73, 0x68, 0x66,
0x75, 0x6C, 0x66, 0x61, 0x63, 0x65, 0x68, 0x61],
[0x49, 0x66, 0x79, 0x6F, 0x75, 0x73, 0x68, 0x65,
0x64, 0x74, 0x65, 0x61, 0x72, 0x73, 0x77, 0x68],
[0x49, 0x74, 0x69, 0x73, 0x74, 0x68, 0x65, 0x74,
0x65, 0x61, 0x72, 0x73, 0x6F, 0x66, 0x74, 0x68],
[0x54, 0x68, 0x61, 0x74, 0x49, 0x65, 0x78, 0x69,
0x73, 0x74, 0x69, 0x73, 0x61, 0x70, 0x65, 0x72],
[0x47, 0x6F, 0x64, 0x65, 0x78, 0x70, 0x65, 0x63,
0x74, 0x73, 0x61, 0x6E, 0x73, 0x77, 0x65, 0x72],
[0x4F, 0x42, 0x65, 0x61, 0x75, 0x74, 0x79, 0x66,
0x69, 0x6E, 0x64, 0x74, 0x68, 0x79, 0x73, 0x65],
])

b = mat([
[179334],
[175544],
[180760],
[182366],
[182850],
[180568],
[181440],
[178347],
[181577],
[176475],
[174043],
[179882],
[178817],
[175345],
[178696],
[175320],
])

X = a.I * b
print(X)

numpy中的 matrixmat 都可以用于生成矩阵结构,mat是matrix的缩写
代码中 a 表示一个16x16的矩阵,代表系数矩阵;b表示一个16x1的矩阵,代表方程组的解。
a.I 代表矩阵a的逆矩阵,用X = a.I * b公式来求出方程组的解
运行结果 X:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[[ 122.]
[ 99.]
[ 116.]
[ 102.]
[ 123.]
[ 87.]
[ 114.]
[ 111.]
[ 110.]
[ 103.]
[ 95.]
[ 70.]
[ 108.]
[ 97.]
[ 103.]
[ 125.]]

PS: 这是在做zctf2016的re100题目时碰到的解方程组问题,想起之前乱翻《Python机器学习实战》的时候,我扫了几眼看到了numpy可以进行矩阵运算,于是直接找出那本书学了一下。

CATALOG
  1. 1. 使用numpy解方程组