Basic Numpy array value assignment

偶尔善良 提交于 2019-12-01 17:54:32

The following may show what's going on:

>>> A = np.array([[2,-1,0],[-1,2,-1],[0,-1,2]])
>>> A.dtype
dtype('int32')
>>> A[0, 1]
-1
>>> A[0, 1] * 0.5
-0.5
>>> A[0, 1] *= 0.5
>>> A[0, 1]
0
>>> int(-0.5)
0

Your array can only hold 32-bit integers, so any floating point value you try to assign to it will be cast, i.e. truncated, to an int32.


For the same price, here's a more numpythonic way of doing what you were after: for loops are generally to be avoided, as they defeat the whole purpose of numpy:

def ldlt_np(arr) :
    rows, cols = arr.shape
    tmp = 1 / np.diag(arr) # this is a float array
    mask = np.tril_indices(cols)
    ret = arr * tmp[:, None] # this will also be a float array
    ret[mask] = arr[mask]

    return ret

>>> A = np.array([[2,-1,0],[-1,2,-1],[0,-1,2]])
>>> ldlt_np(A)
array([[ 2. , -0.5,  0. ],
       [-1. ,  2. , -0.5],
       [ 0. , -1. ,  2. ]])

numpy arrays have fixed type. You can't change an int array to floats later. Initialize the array as an array of floats:

A = numpy.array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]], numpy.float)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!