Basic Numpy Array Value Assignment
As a small exercise before i start playing with numeric code in python I am trying to make an LDLT algorithm. Just to 'get the feet wet'. However I seem to be lacking a fundamental
Solution 1:
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. ]])
Solution 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)
Post a Comment for "Basic Numpy Array Value Assignment"