LU decomposition

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Nov 3 10:52:27 EST 2015


On 1 November 2015 at 10:04, gers antifx <schweiger.gerald at gmail.com> wrote:
>
> I have to write a LU-decomposition. My Code worked so far but (I want to become better:) ) I want to ask you, if I could write this LU-decomposition in a better way?
>
> def LU(x):
>     L = np.eye((x.shape[0]))
>     n = x.shape[0]
>     for ii in range(n-1):
>         for ll in range(1+ii,n):
>             factor = float(x[ll,ii])/x[ii,ii]
>             L[ll,ii] = factor
>             for kk in range(0+ii,n):
>                     x[ll,kk] = x[ll,kk] - faktor*x[ii,kk]
>     LU = np.dot(L,x)

You're using ii and ll, kk etc. This is common practise in Matlab code
because Matlab uses i as sqrt(-1) but this is spelled 1j in Python so
we don't have that problem. In this sort of context it would be more
natural to use simply i, j, k in Python.

Another is that you're not checking for divide by zero in
float(x[ll,ii])/x[ii,ii]. Are you sure that it will not be zero? What
happens if e.g. x[0, 0] is zero? This is where you'll need to use
pivoting which complicates the algorithm a bit.

--
Oscar



More information about the Python-list mailing list