Gauss-Jacobi iteration method - c

I'm trying to write a programm that solves system of equations Ax=B using Gauss-Jacobi iteration method.
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
double **a, *b, *x, *f, eps = 1.e-2, c;
int n = 3, m = 3, i, j, bool = 1, d = 3;
/* printf("n=") ; scanf("%d", &n);
printf("m=") ; scanf("%d", &n) */
a =malloc(n * sizeof *a);
for (i = 0; i < n; i++)
a[i] = (double*)malloc(m * sizeof(double));
b = malloc(m * sizeof *b);
x = malloc(m * sizeof *x) ;
f = malloc(m * sizeof *f) ;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
printf("a[%d][%d]=", i, j);
scanf("%le", &a[i][j]);
if(fabs(a[i][i])<1.e-10) return 0 ;
}
printf("\n") ;
}
printf("\n") ;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
printf("a[%d][%d]=%le ", i, j, a[i][j]);
}
printf("\n") ;
}
for (j = 0; j < m; j++) {
printf("x[%d]=", j);
scanf("%le", &x[j]);
} //intial guess
printf("\n") ;
for (j = 0; j < m; j++) {
printf("b[%d]=", j);
scanf("%le", &b[j]);
}
printf("\n") ;
while (1) {
bool = 0;
for (i = 0; i < n; i++) {
c = 0.0;
for (j = 0; j < m; j++)
if (j != i)
c += a[i][j] * x[j];
f[i] = (b[i] - c) / a[i][i];
}
for (i = 0; i < m; i++)
if (fabs(f[i] - x[i]) > eps)
bool = 1;
if (bool == 1)
for (i = 0; i < m; i++)
x[i] = f[i];
else if (bool == 0)
break;
}
for (j = 0; j < m; j++)
printf("%le\n", f[j]);
return 0;
}
The condition of stoping the loop is that previous approximation minus current approximation for all x is less than epsilon.
It seems like i did everything according to algorithm,but the programm doesn't work.
Where did i make a mistake?

While not the most strict condition, the usual condition requiered to guarantee convergence in the Jacobi and Gauss-Seidel methods is diagonal dominance,
abs(a[i][i]) > sum( abs(a[i][j]), j=0...n-1, j!=i)
This test is also easy to implement as a check to run before the iteration.
The larger the relative gap in all these inequalities, the faster the convergence of the method.

Related

Sorting a matrix

Im trying to sort a matrix by the sum of its row's digits, from highest to lowest. I dont know if i explained that correctly so here's some photos explaining it.
This is what my code outputs. Basically, it asks you for m and n, which are the dimensions of the matrix. In this example it's a 3x4, 3 rows and 4 columns. Then, the matrix should be sorted by rows, by the sum of row's digits. Which means, instead of what's being outputted in the picture above, the correct result should be this:
I have no idea how to sort this from highest to lowest, i have been trying for hours to no avail.
Here's my code:
#include <stdio.h>
#define N 30
void main(){
double a[N][N], s[N], p;
int i, j, m, n, max;
while(1){
printf("\nm, n? ");
scanf("%d%d", &m, &n);
if(m <= 0 || m > N || n <=0 || n > N)
break;
for(i = 0; i < m; i++){
printf("%2d. row? ", i+1);
for(j = 0; j < n; scanf("%lf", &a[i][j++]));
}
for(i = 0; i < m; i++)
for(s[i] = j = 0; j < n; s[i] += a[i][j++]);
for(j = 0; j < n - 1; j++){
for(max = i, j = i+1; j < n; j++)
if(s[j] > s[max])
max = i;
if(max != j){
p = s[j];
s[j] = s[max];
s[max] = p;
for(j = 0; j < m; j++){
p = a[j][i];
a[j][i] = a[j][max];
a[j][max] = p;
}
}
}
printf("New matrix: \n");
for(i = 0; i < m; i++){
for(j = 0; j < n; printf("%8.2lf", a[i][j++]));
printf("\n");
}
for(j = 0; j < m; j++)
printf("-------------");
printf("\n");
for(j = 0; j < m; printf("%8.2f \n", s[j++]));
printf("\n");
}
}
You can sort the rows of the matrix from highest to lowest, using a simple bubble sort algorithm.Your code modified below:
int main() {
double a[N][N], s[N], p;
int i, j, m, n, max;
while (1) {
printf("\nm, n? ");
scanf("%d%d", & m, & n);
if (m <= 0 || m > N || n <= 0 || n > N)
break;
for (i = 0; i < m; i++) {
printf("%2d. row? ", i + 1);
for (j = 0; j < n; scanf("%lf", & a[i][j++]));
}
for (i = 0; i < m; i++)
for (s[i] = j = 0; j < n; s[i] += a[i][j++]);
for (i = 0; i < m - 1; i++) { // modified here
for (j = i + 1; j < m; j++) { // modified here
if (s[j] > s[i]) { // modified here
p = s[i];
s[i] = s[j];
s[j] = p;
for (int k = 0; k < n; k++) {
p = a[i][k];
a[i][k] = a[j][k];
a[j][k] = p;
}
}
}
}
printf("New matrix: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; printf("%8.2lf", a[i][j++]));
printf("\n");
}
for (j = 0; j < m; j++)
printf("-------------");
printf("\n");
for (j = 0; j < m; printf("%8.2f \n", s[j++]));
printf("\n");
}
return 0;
}
Here's how i modified your code to achieve that:
Initialize a loop variable i to 0.
In the outer loop, run the inner loop j from i+1 to m-1.
In the inner loop, compare the sum of the row i with the sum of row
j. If the sum of row j is greater than the sum of row i, swap the
rows using a temporary variable.
After the inner loop finishes, increment the value of i by 1. Repeat
the outer loop until i becomes equal to m-1.
Output:
You can just use qsort to let it handle the sorting and item swapping. Then you only need to write the code for comparing two rows with each other.
Given something like this:
int matrix[3][4] =
{
{1,2,3,4},
{5,6,7,8},
{9,1,2,3},
};
You'd call qsort as:
qsort(matrix, 3, sizeof(int[4]), compare);
The only complexity is implementing the comparison callback function. There's two things to consider there:
We've told qsort that we have an array of 3 items, each of type int[4]. So the void pointers it passes along to us will actually be pointers to type int[4]. That is: int(*)[4].
qsort sorts in ascending order by default, where the item considered "less" ends up first. So we need to tweak that to get the largest item first.
Example:
int compare (const void* obj1, const void* obj2)
{
const int (*ptr1)[4] = obj1;
const int (*ptr2)[4] = obj2;
size_t sum1=0;
size_t sum2=0;
for(size_t i=0; i<4; i++)
{
sum1 += (*ptr1)[i];
sum2 += (*ptr2)[i];
}
if(sum1 > sum2) // largest sum considered "less" for qsort
return -1;
else
return 1;
return 0;
}
sum1 < sum2 would have placed the smallest row first.
Full example:
#include <stdio.h>
#include <stdlib.h>
int compare (const void* obj1, const void* obj2)
{
const int (*ptr1)[4] = obj1;
const int (*ptr2)[4] = obj2;
size_t sum1=0;
size_t sum2=0;
for(size_t i=0; i<4; i++)
{
sum1 += (*ptr1)[i];
sum2 += (*ptr2)[i];
}
if(sum1 > sum2) // largest sum considered "less" for qsort
return -1;
else
return 1;
return 0;
}
void print_matrix(size_t col, size_t row, int matrix[col][row])
{
for(size_t i=0; i<col; i++)
{
for(size_t j=0; j<row; j++)
{
printf("%d,", matrix[i][j]);
}
puts("");
}
}
int main (void)
{
int matrix[3][4] =
{
{1,2,3,4},
{5,6,7,8},
{9,1,2,3},
};
print_matrix(3,4,matrix);
puts("");
qsort(matrix, 3, sizeof(int[4]), compare);
print_matrix(3,4,matrix);
}

Expression must have arithmetic type issue

I need to multiply two square matrixes A and B 15x15.
Unfortunately, I'm getting this kind of error.
I know the problem is in pointers while calculating matrix C.
C[i][j] += *(A + k) * *(B + k)
I hope you can explain me what's wrong. I'm a beginner xD.
Thank you in advance.
#include <stdio.h>
#define N 15
#define _CRT_SECURE_NO_WARNINGS
int main() {
int A[N][N];
int B[N][N];
int C[N][N];
printf("Input matrix A.\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("Enter your element:\n");
scanf_s("%d", &A[i][j]);
}
printf("\n");
}
printf("Input matrix B.\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("Enter your element:\n");
scanf_s("%d", &B[i][j]);
}
printf("\n");
}
printf("Matrix A.\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d\t", A[i][j]);
}
printf("\n");
}
printf("Matrix B.\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d\t", B[i][j]);
}
printf("\n");
}
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
C[i][j] = 0;
for (int k = 0; k < 14; k++) {
C[i][j] += *(A + k) * *(B + k);
k++;
}
}
}
printf("Your result:\n");
printf("Matrix C.\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d\t", C[i][j]);
}
printf("\n");
}
return 0;
}
The problem in the multiplication is that A+k and B+k have type int (*)[15] which means dereferencing it once only makes a pointer out of them; furthermore, you need to take row and column items individually, which means A[i][k] and B[k][j], right? (also, there's no point on using confusing syntax, as the underlying operation is exactly the same).
Here's a fixed and improved version:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define N 15
/* Improvement 1 (type abstraction) */
typedef int NxN_int_matrix[N][N];
/* Improvement 2 (input function & wrapper) */
#define input_matrix(var) input_matrix_ex((var), #var)
static void input_matrix_ex(NxN_int_matrix dst, char *name)
{
printf("Input matrix %s.\n", name);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
/* Improvement 3 (nicer prompt) */
printf("%s[%2d][%2d]: ", name, i, j);
fflush(stdout);
scanf_s("%d", &dst[i][j]);
}
}
printf("\n");
}
/* Improvement 4 (print function) */
#define print_matrix(var) print_matrix_ex(#var, (var))
static void print_matrix_ex(char *name, NxN_int_matrix M)
{
printf("Matrix %s.\n", name);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d\t", M[i][j]);
}
printf("\n");
}
}
/* Improvement 5 (move multiplication to a function too, and fix it) */
static void mult_matrix(NxN_int_matrix dst, NxN_int_matrix a, NxN_int_matrix b)
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
/* Improvement 6 (don't write out intermediate values) */
int tmp = 0;
for (int k = 0; k < N; k++)
tmp += a[i][k] * b[k][j];
dst[i][j] = tmp;
}
}
}
int main()
{
NxN_int_matrix A, B, C;
input_matrix(A);
input_matrix(B);
print_matrix(A);
print_matrix(B);
mult_matrix(C, A, B);
printf("Your result:\n");
print_matrix(C);
return 0;
}
/* Possible further improvements:
* - using a transposed B might make multiplication faster
*/

Why are random values shown as output to find determinant of a matrix?

I wanted to find determinant of a M*M matrix by using recursion in C.
Here is the code I have tried in Ubuntu.
// Computing determinant of a MXM matrix
#include <stdio.h>
int determinant(int M, int A[10][10]) { //Function to calculate det(A)
int i, j, k, m, n, p, q, pow = 1;
int B[10][10];//assuming M does not cross 10
if (M == 1)
return A[0][0];
else {
det = 0;
for (k = 0; k < M; k += 1) {
m = 0;
n = 0; //m,n are indices of subdeterminant of A
for (i = 0; i < M; i += 1) {
for (j = 0; j < M; j += 1) {
if (i != 0 && j != k) {
B[m][n] = A[i][j]; //finding submatrix
if (n < (k - 2))
n += 1;
else {
n = 0;
m += 1;
}
}
}
}
det += pow * (A[0][k] * determinant(M - 1, B));
pow = -1 * pow;
}
return det;
}
}
int main() {
int M, i, j; // M is order of matrix A for which determinant has to be found
printf("Enter the order of matrix: ");
scanf("%d", &M);
int A[10][10];
printf("Enter matrix A: ");
for (i = 0; i < M; i += 1) {
for (j = 0; j < M; j += 1) {
scanf("%d", &A[i][j]); //Entering elements of matrix A
}
}
printf("Given matrix A is: \n");
for (i = 0; i < M; i += 1) {
for (j = 0; j < M; j += 1) {
printf("%d ", A[i][j]);
}
printf("\n");
}
int det = determinant(M, A);
printf("The determinant of given matrix is %d\n", det);
return 0;
}
This code works fine for a matrix of order 2. But for higher orders, the output is some random number. I am unable to identify any mistake in this. Can anyone explain why the output is not as expected and how to rectify the code to get the expected output?
The inner loop that extracts the submatrix B from A seems broken.
Here is a simpler version:
for (i = 1, m = 0; i < M; i++, m++) {
for (j = 0, n = 0; j < k; j++, n++)
B[m][n] = A[i][j];
for (j = k + 1; j < M; j++, n++)
B[m][n] = A[i][j];
}

Why does my C program that is supposed to output a matrix to the power of n output my matrix to the power of 2^n?

My code is supposed to take in a matrix M and raise it to the power of an integer A. However, somehow, my output is always M^(2^A). For example, if I want to find a matrix in its 3rd power, I will instead receive its 8th power.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void multiply(int ** p, int pwr, int dim, int ** prod) {
int m, i, j, k;
/*if (n<pwr){*/
int pos = 0;
for (m = 0; m < pwr; m++) {
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
for (k = 0; k < dim; k++) {
pos += p[i][k] * p[k][j];
}
prod[i][j] = pos;
pos = 0;
}
}
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
p[i][j] = prod[i][j];
prod[i][j] = 0;
}
}
}
/*n=n+1;
multiply(prod, q, pwr, dim, prod);
}*/
}
int main(int argc, char * argv[]) {
FILE * fp = fopen(argv[1], "r");
int dim, pwr, i, j;
fscanf(fp, "%d", & dim);
int ** matrix;
matrix = (int ** ) malloc(dim * sizeof(int * ));
for (i = 0; i < dim; i++) {
matrix[i] = (int * ) malloc(dim * sizeof(int));
}
int ** prod;
prod = (int ** ) malloc(dim * sizeof(int * ));
for (i = 0; i < dim; i++) {
prod[i] = (int * ) malloc(dim * sizeof(int));
}
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
fscanf(fp, "%d", & matrix[i][j]);
}
}
fscanf(fp, "%d", & pwr);
if (pwr == 1) {
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
} else if (pwr >= 2) {
multiply(matrix, pwr, dim, prod);
for (i = 0; i < dim; i++) {
for (j = 0; j < dim; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
return 0;
}
You are multiplying your matrix by itself and then store the result in the original one. Then you do it again.
So perfectly normal that it gets powered 8 times. What you need is another temporary matrix on which you store the result and keep the original matrix to multiply your result with.

Why does my code return -nan in visual studio, but not in Linux?

My Gauss Elimination code's results are -nan in visual studio, but not in Linux.
And the Linux results are awful because at func Gauss_Eli how many I increase the variable k at for blocks the func is working... doesn't occur segment error.
What is wrong with my code?
float ** Gauss_Eli(float ** matrix, int n) {
// -----------------------------------------------------
// | |
// | Eliminate elements except (i, i) element |
// | |
// -----------------------------------------------------
// Eliminate elements at lower triangle part
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = 0; k < n + 1; k++) {
float e;
e = matrix[i][k] * (matrix[j][i] / matrix[i][i]);
matrix[j][k] -= e;
}
}
}
// Eliminate elements at upper triangle part
for (int i = n - 1; i >= 0; i--) {
for (int j = i - 1; j >= 0; j--) {
for (int k = 0; k < n + 1; k++) {
float e;
e = matrix[i][k] * (matrix[j][i] / matrix[i][i]);
matrix[j][k] -= e;
}
}
}
// Make 1 elements i, i
for (int i = 0; i < n; i++)
for (int j = 0; j < n + 1; j++) matrix[i][j] /= matrix[i][i];
return matrix;
}
int main() {
float ** matrix;
int n;
printf("Matrix Size : ");
scanf("%d", &n);
// Malloc variable matrix for Matrix
matrix = (float**)malloc(sizeof(float) * n);
for (int i = 0; i < n; i++) matrix[i] = (float*)malloc(sizeof(float) * (n + 1));
printf("Input elements : \n");
for (int i = 0; i < n; i++)
for (int j = 0; j < n + 1; j++) scanf("%f", &matrix[i][j]);
matrix = Gauss_Eli(matrix, n);
printf("Output result : \n");
//Print matrix after elimination
for (int i = 0; i < n; i++) {
for (int j = 0; j < n + 1; j++) printf("%.6f ", matrix[i][j]);
printf("\n");
}
return 0;
}
1.) OP allocates memory using the wrong type. This may lead to issues of insufficient memory and all sorts of UB and explain the difference between systems as they could have differing pointer and float sizes.
float ** matrix;
// v--- wrong type
// matrix = (float**)malloc(sizeof(float) * n);
Instead allocate to the size of the referenced variable. Easier to code (and get right), review and maintain.
matrix = malloc(sizeof *matrix * n);
if (matrix == NULL) Handle_Error();
2.) Code should look for division by 0.0
//for (int k = 0; k < n + 1; k++) {
// float e;
// e = matrix[i][k] * (matrix[j][i] / matrix[i][i]);
// matrix[j][k] -= e;
//}
if (matrix[i][i] == 0.0) Handle_Error();
float m = matrix[j][i] / matrix[i][i];
for (int k = 0; k < n + 1; k++) {
matrix[j][k] -= matrix[i][k]*m;
}
3.) General problem solving tips:
Check return values of scanf("%f", &matrix[i][j]);. It is 1?
Enable all warnings.
Especially for debug, print FP using "%e" rather than "%f".
4.) Numerical analysis tip: Insure exact subtraction when i==j
if (i == j) {
for (int k = 0; k < n + 1; k++) {
matrix[j][k] = 0.0;
}
else {
if (matrix[i][i] == 0.0) Handle_Divide_by_0();
float m = matrix[j][i] / matrix[i][i];
for (int k = 0; k < n + 1; k++) {
matrix[j][k] -= matrix[i][k]*m;
}
}

Resources