i was trying to write Gaussian elimination method on C
Code:
float M[4][5] =
{
{99.69, 7.07, 53, -4, 155.76},
{-138.41, 14.11, -6.31, 5.6, -124.74},
{55, 35.174, 685, 1.4, 776.574},
{33, 21, -3.28, -0.28, 50.44}
};
float t_arr[5] = {0,0,0,0,0};
for(int j = 0; j < 5; j )
{
t_arr[j] = M[2][j];
t_arr[j] *= (-(M[3][0]/M[2][0]));
printf("t_arr[%d] = %f\n",j, t_arr[j]);
M[3][j] = t_arr[j];
}
Error appears here:
t_arr[j] *= (-(M[3][0]/M[2][0]));
As i wanted it to be is that third row of matrix M[2][j] == t_arr[j]
That works, but after multiplying values of `t_arr[j] to (-(M[3][j]/M[2][0]))
F.e
t_arr[0] * (-(M[3][0]/M[2][0]))
==>> 55 * -33\55 = -33
It Outputs:
t_arr[0] = -33.000000
t_arr[1] = -0.000000
t_arr[2] = -0.000000
t_arr[3] = -0.000000
t_arr[4] = -0.000000
CodePudding user response:
M[3][j] = t_arr[j];
in the first iteration will turn the value of M[3][0]
to zero because the initial value of M[3][0]
is 33
and the calculated value of t_arr[0]
is -33.000000
.
If you want to use the initial value of M[3][0]
and M[2][0]
in all iterations, you should do the calculation of -(M[3][0]/M[2][0])
and save the result before the loop.
float M[4][5] =
{
{99.69, 7.07, 53, -4, 155.76},
{-138.41, 14.11, -6.31, 5.6, -124.74},
{55, 35.174, 685, 1.4, 776.574},
{33, 21, -3.28, -0.28, 50.44}
};
float t_arr[5] = {0,0,0,0,0};
float multiplier = (-(M[3][0]/M[2][0]);
for(int j = 0; j < 5; j )
{
t_arr[j] = M[2][j];
t_arr[j] *= multiplier;
printf("t_arr[%d] = %f\n",j, t_arr[j]);
M[3][j] = t_arr[j];
}
CodePudding user response:
After this statement in the first iteration of the loop
M[3][j] = t_arr[j];
the value of M[3][0]
is equal to 0
( 33.0 -33.0
).
So this expression (-(M[3][0]/M[2][0]))
will always evaluate to 0 in subsequent iterations of the loop.