Assigning a value to a Basic Numpy array

As a little exercise, before I start playing with numeric code in python, I am trying to create an LDLT algorithm. Just to "get your feet wet."

However, it seems that I am missing a fundamental understanding of the numpy array. See the following example:

def ldlt(Matrix):
    import numpy

    (NRow, NCol) = Matrix.shape

    for col in range(NCol):
        Tmp = 1/Matrix[col,col]
        for D in range(col+1, NCol):
            Matrix[col,D] = Matrix[D,col]*Tmp  

if __name__ == '__main__':
    import numpy
    A = numpy.array([[2,-1,0],[-1,2,-1],[0,-1,2]])
    ldlt(A)

The example is not the complete code I'm working on. However, try starting it and set a breakpoint in Matrix [col, D] = ...

What I expect for the first assessment is that column 1 of row 0 (initial value -1) is set to = -1 * (1/2) = -0.5.

However, when you run the code, it seems to be 0. Why? There must be something fundamental that I really didn't understand?

Thanks in advance to all of you guys helping me.

EDIT 1:

Python Ver .: 3.3 Tmp: will become 0.5 (As reported by my debugger).

+5
2

, :

>>> 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

32- , , , , .. , int32.


, numpythonic , : , , , 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. ]])
+3

numpy . int . :

A = numpy.array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]], numpy.float)
0

All Articles