Skip to main content
 首页 » 编程设计

python之numpy中的矩阵 reshape 和乘法

2025年05月04日14bonelee

我在玩 numpy 并决定编写以下代码:

import numpy as np 
x = np.arange(9).reshape((3,3)) 
y = np.matrix(x) 
print y**100 

它返回一个元素为零的矩阵。但是,当我使用 Wolframealpha , 它给出了一个非零矩阵。

请您参考如下方法:

您的 y 矩阵具有整数 dtype,与标准 Python 整数不同,numpy 的 int 类型不是任意精度。您可以使用 dtype=object,用 Python int 填充矩阵,或者如果您不关心所有的,则使用 float数字:

>>> y = np.matrix(x) 
>>> y.dtype 
dtype('int32') 
>>> y**100 
matrix([[0, 0, 0], 
        [0, 0, 0], 
        [0, 0, 0]]) 
>>> y = np.matrix(x, dtype=object) 
>>> y**100 
matrix([[ 2670418853448576713687852704912671527970511575728810365950424084797868760412259003135073323381718297176682004480L, 
         3444567800850282079692781034870828183553947660529812540319833584768259983314213940415516918334371346607654305792L, 
         4218716748251987445697709364828984839137383745330814714689243084738651206216168877695960513287024396038626607104L], 
        [ 8197368319791984868128060940682347328285433721006389328199161486466484941612834618738492096297739402081617313792L, 
         10573768579262836262345700893588106900651176751244677722138825437315597420762144957899979685279423429818598817792L, 
         12950168838733687656563340846493866473016919781482966116078489388164709899911455297061467274261107457555580321792L], 
        [ 13724317786135393022568269176452023128600355866283968290447898888135101122813410234341910869213760506986552623104L, 
         17702969357675390444998620752305385617748405841959542903957817289862934858210075975384442452224475513029543329792L, 
         21681620929215387867428972328158748106896455817635117517467735691590768593606741716426974035235190519072534036480L]], dtype=object) 
>>> y = np.matrix(x, dtype=float) 
>>> y**100 
matrix([[  2.67041885e+111,   3.44456780e+111,   4.21871675e+111], 
        [  8.19736832e+111,   1.05737686e+112,   1.29501688e+112], 
        [  1.37243178e+112,   1.77029694e+112,   2.16816209e+112]])