2014-02-22 101 views
1

我用numpy的演奏和决定写代码如下:矩阵整形和乘法numpy的

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

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

回答

5

您的y矩阵有一个整数dtype,与标准的Python整数不同,numpy的int类型不是任意的精度。您可以使用dtype=object,填补与Python int S上的矩阵,或者使用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]]) 
1

在MATLAB你

>> y = [0 1 2; 3 4 5; 6 7 8] 

y = 

    0  1  2 
    3  4  5 
    6  7  8 

>> y^2 

ans = 

    15 18 21 
    42 54 66 
    69 90 111 

>> y^100 

ans = 

    1.0e+112 * 

    0.2670 0.3445 0.4219 
    0.8197 1.0574 1.2950 
    1.3724 1.7703 2.1682 

在蟒蛇numpy ,如果你使用正确的数据类型,你会得到相同的:

>>> x = np.arange(9).reshape((3,3)) 

>>> print x 
[[0 1 2] 
[3 4 5] 
[6 7 8]] 
>>> y = np.matrix(x, dtype="float64") 
>>> y 
matrix([[ 0., 1., 2.], 
     [ 3., 4., 5.], 
     [ 6., 7., 8.]]) 
>>> 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]]) 
0

我有我用numpys幂函数类似的问题:

np.power(y.astype(float), 100) 

由于DSM表示数据类型存在问题,但仍然为0 ** 100应为零。