#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void Jocabi(int n, double A[][25], double b[], double x[], double eps, int MaxStep);
double sum(int n, int i, double A[][25], double x[], double b[]);
double _max(double a, double b);
int main(){
int n;
double A[25][25], b[25], x[25];
double eps = 1e-6;
int MaxStep = 1000;
scanf("%d", &n);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
scanf("%lf", &A[i][j]);
}
}
for(int i = 0; i < n; i++) scanf("%lf", &b[i]);
for(int i = 0; i < n; i++) scanf("%lf", &x[i]);
Jocabi(n, A, b, x, eps, MaxStep);
}
double sum(int n, int i, double A[][25], double x[], double b[]) {
double ret=b[i];
for (int j=0; j<n; j++) {
if (j != i) {
ret -= A[i][j] * x[j];
}
}
return ret;
}
double _max(double a, double b) {
return a > b ? a : b;
}
void Jocabi(int n, double A[][25], double b[], double x0[], double eps, int MaxStep){
double x[25];
int cnt = 0;
double err = eps + 1.0;
while(err > eps && cnt < MaxStep){
err = 0;
double x0[25];
for (int u=0; u<n; u++) {
x0[u] = x[u];
}
for (int i=0; i<n; i ++) {
x[i] = sum(n, i, A, x0, b) / A[i][i];
err = _max(err, fabs(x[i] - x0[i]) / (1.0 + fabs(x[i])));
}
cnt ++;
}
if (cnt < 1000) {
for (int k=0; k<n; k ++) {
printf("%lf ", x[k]);
}
} else {
printf("Fail.");
}
}
Jacobi迭代法
最新推荐文章于 2024-08-29 07:41:07 发布