-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjacobi_method.c
106 lines (87 loc) · 2.15 KB
/
jacobi_method.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include <stdlib.h>
#include "utils.h"
double *calculateJacobi(double **A, double *b, double *x, int rows, int cols, int n)
{
// Temporary array for new values
double *x_new = malloc(sizeof(double) * rows);
for (int iter = 0; iter < n; iter++)
{
for (int i = 0; i < rows; i++)
{
double sigma = 0;
for (int j = 0; j < rows; j++)
{
if (j != i)
{
sigma += A[i][j] * x[j];
}
}
x_new[i] = (1.0 / A[i][i]) * (b[i] - sigma);
}
// Update x with new values
for (int i = 0; i < rows; i++)
{
x[i] = x_new[i];
}
}
// Free the temporary array
free(x_new);
return x;
}
int main()
{
// Declaration number of linear equations, number of unknown variables
int rows = 3, cols = 3;
// Init matrix
double **A = (double **)malloc(sizeof(double *) * rows);
for (int i = 0; i < rows; i++)
{
A[i] = (double *)malloc(sizeof(double) * cols);
};
// Fill matrix
A[0][0] = 5;
A[0][1] = -2;
A[0][2] = 3;
A[1][0] = -3;
A[1][1] = 9;
A[1][2] = 1;
A[2][0] = 2;
A[2][1] = -1;
A[2][2] = -7;
// Print matrix
printf("Matrix with %d rows and %d cols.\n", rows, cols);
printMatrix(A, rows, cols, 2);
// Init b vector
double *b = malloc(sizeof(double) * rows);
// Fill vector
b[0] = -1;
b[1] = 2;
b[2] = 3;
// Print vector b
printf("Vector with size %d.\n", rows);
printVector(b, rows, 2);
// Init x vector
double *x = malloc(sizeof(double) * rows);
// Fill vector
x[0] = 0;
x[1] = 0;
x[2] = 0;
// Print vector x
printf("Vector with size %d.\n", rows);
printVector(x, rows, 2);
// Iterate with Jacobi method
x = calculateJacobi(A, b, x, rows, cols, 2);
// Print result vector x
printf("Vector with size %d.\n", rows);
printVector(x, rows, 4);
// Free allocated memory
for (int i = 0; i < rows; i++)
{
free(A[i]);
}
free(A);
free(b);
free(x);
return 0;
};