简体   繁体   English

正向替换无法在C语言中按预期工作

[英]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. 我试图编写代码以在线性方程Ax=B的系统中找到A ,所以我使用了LU分解。 Now that I have L and U properly, I'm stuck in the forward substitution in order to get the y in B=Ly. 现在我已经正确地拥有了L和U,为了得到B = Ly中的y,我被困在正向替换中。

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. 我在MatLab上编写了一些可以完美工作的代码,但是用C重写代码却无法获得相同的结果。所以我想知道是否有人可能知道我在做错什么,所以我不完全习惯C。

Here's my code in MatLab: 这是我在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. 其中L是我的下三角矩阵, B是相同大小的向量,在这种情况下, n是2498。

My C code is the following: 我的C代码如下:

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.) 这些代码之间的区别在于,您更改了for循环索引以使其与C中从零开始的索引一起工作。(我无法运行MATLAB版本,并且没有代码的某些上下文,因此可能会有其他差异。)

The variables i and k have values which are smaller by 1 in the C code. 变量ik在C代码中具有小于1的值。 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 . 这正是循环索引所需要的,但是当您使用i来控制k的内部循环中的迭代次数时,就会出现问题。 This is i-1 in both versions of the code, even though i has different values. 即使i具有不同的值,这两个版本的代码都为i-1 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. 例如,在外循环的第一次迭代中,内循环在MATLAB代码中运行一次,而在C语言中根本不运行。

A possible fix would be to rewrite the inner loop in the C code as 可能的解决方法是将C代码中的内部循环重写为

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?). 第二个区别是您要在MATLAB代码中将sum重置为零,而不是在C语言sum2其重置为零(MATLAB代码中还有一个sum2似乎没有被使用?)。 This will cause differences in y_prev[i] for i>0 . 对于i>0这将导致y_prev[i]差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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