LU Decomposition from Numerical Recipes not working; what am I doing wrong?

后端 未结 4 2078
小鲜肉
小鲜肉 2021-01-13 23:01

I\'ve literally copied and pasted from the supplied source code for Numerical Recipes for C for in-place LU Matrix Decomposition, problem is its not working.

I\'m s

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 23:06

    I think there's something inherently wrong with your indices. They sometimes have unusual start and end values, and the outer loop over j instead of i makes me suspicious.

    Before you ask anyone to examine your code, here are a few suggestions:

    • double-check your indices
    • get rid of those obfuscation attempts using sum
    • use a macro a(i,j) instead of a[i*MAT1+j]
    • write sub-functions instead of comments
    • remove unnecessary parts, isolating the erroneous code

    Here's a version that follows these suggestions:

    #define MAT1 3
    #define a(i,j) a[(i)*MAT1+(j)]
    
    int h_NR_LU_decomp(float *a, int *indx)
    {
            int i, j, k;
            int n = MAT1;
    
            for (i = 0; i < n; i++) {
                    // compute R
                    for (j = i; j < n; j++)
                            for (k = 0; k < i-2; k++)
                                    a(i,j) -= a(i,k) * a(k,j);
    
                    // compute L
                    for (j = i+1; j < n; j++)
                            for (k = 0; k < i-2; k++)
                                    a(j,i) -= a(j,k) * a(k,i);
            }
    
            return 0;
    }
    

    Its main advantages are:

    • it's readable
    • it works

    It lacks pivoting, though. Add sub-functions as needed.


    My advice: don't copy someone else's code without understanding it.

    Most programmers are bad programmers.

提交回复
热议问题