Numpy 函数库基础

打开anaconda prompt

(base) C:\Users\LLJiang>python
Python 2.7.14 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:34:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from numpy import *
>>> random.rand(4,4)
array([[ 0.79587355,  0.51178721,  0.95759781,  0.32149325],
       [ 0.32674276,  0.69178829,  0.84330809,  0.33330203],
       [ 0.42283317,  0.48272514,  0.34505398,  0.13832752],
       [ 0.14112735,  0.60516239,  0.71531527,  0.28238856]])

Numpy库中存在两种不同数据类型,矩阵(matrix)和数组(array)。
mat()函数可以将数组转化为矩阵

>>> randMat=mat(random.rand(4,4))
>>> randMat
matrix([[ 0.24805831,  0.47924076,  0.50274741,  0.78345218],
        [ 0.71172631,  0.84472154,  0.56966673,  0.68065404],
        [ 0.48066208,  0.62712967,  0.39504646,  0.62616554],
        [ 0.36492104,  0.99652375,  0.11588792,  0.74867227]])
#.I实现求逆运算
>>> randMat.I
matrix([[ -4.24751193e+00,  -4.89217135e+00,   1.30543914e+01,
          -2.02573471e+00],
        [  1.74255391e+00,   5.85196009e+00,  -1.13438675e+01,
           2.34384399e+00],
        [  3.70582062e+00,   6.92935699e+00,  -1.21797087e+01,
           8.93029683e-03],
        [ -8.22722776e-01,  -6.47731981e+00,   1.06215933e+01,
          -7.98076698e-01]])
>>> invRandMat=randMat.I
>>> randMat*invRandMat

正常来讲,结果应该是单位矩阵,即仅对角线元素是1,其他元素都是0。
然而输出如下:

matrix([[  1.00000000e+00,  -3.34729040e-16,   7.05419710e-16,
           3.54617276e-17],
        [ -5.43814156e-17,   1.00000000e+00,   9.19990930e-16,
          -2.72275645e-16],
        [ -2.57918414e-16,  -3.09633559e-16,   1.00000000e+00,
          -2.96406961e-16],
        [ -2.99592886e-18,  -8.77452587e-16,   1.19584022e-16,
           1.00000000e+00]])

这是计算机处理误差产生的结果。

>>> myEye=randMat*invRandMat
#eye(4)即创建4*4的单位矩阵
>>> myEye-eye(4)
matrix([[  0.00000000e+00,  -3.34729040e-16,   7.05419710e-16,
           3.54617276e-17],
        [ -5.43814156e-17,  -3.33066907e-16,   9.19990930e-16,
          -2.72275645e-16],
        [ -2.57918414e-16,  -3.09633559e-16,   8.88178420e-16,
          -2.96406961e-16],
        [ -2.99592886e-18,  -8.77452587e-16,   1.19584022e-16,
          -1.11022302e-16]])

以上命令即可得到误差值。

猜你喜欢

转载自blog.csdn.net/lulujiang1996/article/details/79001495