简体   繁体   中英

Forward substitution doesn't work as expected in C

I'm trying to write code to find A in a system of linear equations Ax=B , so I used LU decomposition. Now that I have L and U properly, I'm stuck in the forward substitution in order to get the y in B=Ly.

I wrote some code in MatLab that works perfectly, but I can't get the same results rewriting the code in C. So I was wondering if someone may know what i'm doing wrong, I'm not fully used to C.

Here's my code in MatLab:

y(1,1) = B(1,1)/L(1,1);
for i= 2:n
    sum=0;
    sum2=0;
    for k = 1: i-1
        sum = sum + L(i,k)*y(k,1);
    end
    y(i,1)=(B(i,1)-sum)/L(i,i);
end

where L is my lower triangle matrix, B is a vector of the same size, and n is 2498 in this case.

My C code is the following:

float sum = 0;

y_prev[0]=B[0]/(float)Low[0][0];

for (int i = 1; i < CONST; i++)
{
    for (int k = 0; k < i-1; k++)
    {
        sum = sum +Low[i][k]*y_prev[k];
    }

    y_prev[i]= (B[i]- sum)/(float)Low[i][i];
}

One difference between the codes comes from the way you've changed the for loop indices to work with the zero based indexing in C. (I can't run the MATLAB version, and don't have some of the context for the code, so there may be other differences.)

The variables i and k have values which are smaller by 1 in the C code. This is exactly what you want for the loop indices, but a problem arises when you use i to control the number of iterations in the inner loop over k . This is i-1 in both versions of the code, even though i has different values. For instance, in the first iteration of the outer loop the inner loop runs once in the MATLAB code but not at all in the C one.

A possible fix would be to rewrite the inner loop in the C code as

for (int k = 0; k < i; k++)
{
    sum = sum +Low[i][k]*y_prev[k];
}

A second difference is that you're resetting sum to zero in the MATLAB code but not in the C (the MATLAB code also has a sum2 which doesn't seem to be used?). This will cause differences in y_prev[i] for i>0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM