简体   繁体   中英

Why does numpy automatically change type to list when using a variable

I"m trying to add two matrices together, one of whom will use a variable:

import numpy as np
x = 0.1
I_M = np.matrix([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])
e_M = np.matrix([[0.,x/2.,0.],[x/2.,0.,0.],[x**2/(4-x**2)]])
I_M + e_M

Which throws the error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-2f9e17b404f3> in <module>()
      3 I_M = np.matrix([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])
      4 e_M = np.matrix([[0.,x/2.,0.],[x/2.,0.,0.],[x**2/(4-x**2)]])
----> 5 I_M + e_M

TypeError: unsupported operand type(s) for +: 'float' and 'list'

The cause seems to be that numpy is converting the contents of e_M to lists under the hood:

I_M, e_M
(matrix([[1., 0., 0.],
         [0., 1., 0.],
         [0., 0., 1.]]),
 matrix([[list([0.0, 0.05, 0.0]), list([0.05, 0.0, 0.0]),
          list([0.0025062656641604013])]], dtype=object))

Why is numpy doing this, and is there a good work-around that can be recommended?

The problem is that your last row in e_M has only one item, and then to correct for that asymmetry numpy makes all rows of same type , yielding a 3 x 1 matrix of the same object list

Notice that if you correct your last row to have three items, it works as intended:

>>> e_M = np.matrix([[0.,x/2.,0.],[x/2.,0.,0.],[x**2/(4-x**2)]])
matrix([[list([0.0, 0.05, 0.0]), list([0.05, 0.0, 0.0]),
     list([0.0025062656641604013])]], dtype=object)

>>> e_M = np.matrix([[0.,x/2.,0.],[x/2.,0.,0.],[1,1, x**2/(4-x**2)]])
matrix([[0.        , 0.05      , 0.        ],
    [0.05      , 0.        , 0.        ],
    [1.        , 1.        , 0.00250627]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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