繁体   English   中英

numpy中的矩阵重塑和乘法

[英]Matrix reshaping and multiplication in numpy

我在玩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]])

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

我使用numpys power函数时遇到了类似的问题:

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

正如DSM所说,数据类型存在问题,但0 ** 100仍应为零。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM