NumPy 函数库基础
random.rand(4,4)
上述命令构造了4*4的随机数组
>>> random.rand(4,4)
array([[ 0.0418002 , 0.20941796, 0.68781548, 0.32148814], [ 0.39318817, 0.46766914, 0.49318351, 0.65444726], [ 0.33036255, 0.70759215, 0.59520003, 0.77778407], [ 0.26214824, 0.00094159, 0.36463589, 0.40976128]])
调用mat函数可将数组转化为矩阵
>>> randmat=mat(random.rand(4,4))
>>> randmat
matrix([[ 0.28896205, 0.50331665, 0.86803514, 0.9849008 ], [ 0.36103918, 0.69719876, 0.65216554, 0.68634146], [ 0.7609746 , 0.13391717, 0.9644368 , 0.93625736], [ 0.46729404, 0.90324785, 0.05564003, 0.42958976]])
.I 操作符实现了矩阵的求逆运算
>>> randmat.I
matrix([[-1.86271551, 0.16951393, 1.52258776, 0.68137463], [-0.8292055 , 2.16002072, -0.71476897, 0.00787049], [-2.37301311, 4.75169593, 0.09565685, -2.35960664], [ 4.07702559, -5.34144809, -0.16575117, 1.87569013]])
invrandmat=randmat.I
执行此操作存储逆矩阵,接着执行矩阵的乘法:
>>> randmat*invrandmat
matrix([[ 1.00000000e+00, 0.00000000e+00, 0.00000000e+00, -2.22044605e-16], [ 0.00000000e+00, 1.00000000e+00, 0.00000000e+00, -2.22044605e-16], [ 0.00000000e+00, 0.00000000e+00, 1.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 4.99600361e-16, -1.11022302e-16, 1.00000000e+00]])
结果应该为单位矩阵,除了对角线全为1其余元素应全为0,实际输出结果矩阵里还留下了非常小的元素,是计算机处理产生误差的结果,用下述命令求误差值:
>>> myeye=randmat*invrandmat
>>> myeye-eye(4)
matrix([[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -2.22044605e-16], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, -2.22044605e-16], [ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, 4.99600361e-16, -1.11022302e-16, -2.22044605e-16]])
eye(4)创建4*4 单位矩阵
numpy.eye(N,M=None, k=0, dtype=< type ‘float’>)
第一个参数N = 列数
第二个参数 M = 行数,省略代表M = N
第三个参数 k 代表对角线位置, = 0 代表主对角线, +1就向右上方偏移1, -1 就向左下角偏移1
第四个参数表示类型 dtype 默认为 float 类型
>>> e1 = eye(2, 3, 0, dtype = int)
>>> e1
array([[1, 0, 0], [0, 1, 0]])
>>> e2 = eye(3)
>>> e2
array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]])
>>> e3 = eye(3, dtype = int)
>>> e3
array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
>>> e4 = eye(3, 1, dtype = int)
>>> e4
array([[1], [0], [0]])
>>> e5 = eye(3, k = 1, dtype = int)
>>> e5
array([[0, 1, 0], [0, 0, 1], [0, 0, 0]])
>>> e6 = eye(3, k = -1, dtype = int)
>>> e6
array([[0, 0, 0], [1, 0, 0], [0, 1, 0]])
>>>