double *cholesky(double *A, int n) {
double *L = (double*)calloc(n * n, sizeof(double));
if (L == NULL)
exit(EXIT_FAILURE);
for (int i = 0; i < n; i++)
for (int j = 0; j < (i+1); j++) {
double s = 0;
for (int k = 0; k < j; k++)
s += L[i * n + k] * L[j * n + k];
L[i * n + j] = (i == j) ?
sqrt(A[i * n + i] - s) :
(1.0 / L[j * n + j] * (A[i * n + j] - s));
}
return L;
}
Now my question with this code is a follows, I am trying to see the step by step but I am getting a bit confused.
when I write
for(condition)
for(condition){
For(k=0;k<j;k++)
s += L[i * n + k] * L[j * n + k];
L[i * n + j] = (i == j) ?
sqrt(A[i * n + i] - s) :
(1.0 / L[j * n + j] * (A[i * n + j] - s));
}
This is what I see happening:
First i = 0
and j = 0
; then I step further into the code and we get this: for(k)
loop. Now my first question is this since j=0
in first instance this for loop does not get evaluated, since k
is less than j
.
for (int k = 0; k < j; k++)
But what of the kode below this for loop does get evaluated.
Since L
is an array of zeros, then s+=l[0]*l[0]
should equal 0
, but I dont get how the loop did run at all. Next does everything else below the for(k)
get evaluated?
if so i==j
is true so L[i * n + j] = sqrt(A[i * n + i] - s)
(in this case equals 0).
now going back to the top my nest questions becomes since
for(condition i )
for(condition j)
don't have brackets does for(i=1 )
get evaluated following that for(j)
gets evaluated twice below before j=0
and j=i
?
Really would appreciate all the help I could get.
Thank you,