Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #98035

Re: LU decomposition

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: LU decomposition
Date 2015-11-01 21:18 +1100
Message-ID <mailman.14.1446373125.4463.python-list@python.org> (permalink)
References <1e6c4ce1-885c-43ac-b0a5-054f46d4c96e@googlegroups.com>

Show all headers | View raw


On Sun, Nov 1, 2015 at 9:04 PM, gers antifx <schweiger.gerald@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)

For a start, I would recommend being careful with your variable names.
You have 'factor' all except one, where you have 'faktor' -
transcription error, or nearly-identical global and local names? And
all your other names are fairly opaque; can they be better named? I'm
particularly looking at this line:

x[ll,kk] = x[ll,kk] - faktor*x[ii,kk]

It is *extremely not obvious* that the first two are using 'll' and
the last one is using 'ii'. (Though I would write this as "x[ll,kk] -=
faktor*x[ii,kk]", which at least cuts down the duplication, so it's
less glitchy to have one out of three that's different.) I was going
to ask if you had some reason for not inverting the factor and simply
using "x[ll,kk] *= factor", till I read it again and saw the
difference.

I'm seeing here a lot of iteration over ranges, then subscripting with
that. Is it possible to iterate over the numpy array itself instead?
That's generally a more Pythonic way to do things.

Assigning to the local name LU at the end of the function seems odd.
Did you intend to return the dot-product?

Beyond that, I'd need a better comprehension of the mathematics behind
this, to evaluate what it's doing. So I'll let the actual experts dive
in :)

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

LU decomposition gers antifx <schweiger.gerald@gmail.com> - 2015-11-01 02:04 -0800
  Re: LU decomposition Chris Angelico <rosuav@gmail.com> - 2015-11-01 21:18 +1100
  Re: LU decomposition Peter Otten <__peter__@web.de> - 2015-11-01 12:55 +0100
  Re: LU decomposition Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2015-11-03 15:52 +0000
  Re: LU decomposition Nagy László Zsolt <gandalf@shopzeus.com> - 2015-11-03 19:21 +0100

csiph-web