numpy中的矩阵重塑和乘法

时间:2014-02-22 15:07:18

标签: python numpy

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

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

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

3 个答案:

答案 0 :(得分:5)

您的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]])

答案 1 :(得分: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

在python 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]])

答案 2 :(得分:0)

我有类似的问题,我使用了numpys power function:

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

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