線性方程
解決線性方程有兩類方法:
-
直接方法 : 直接方法的共同特徵是它們將原始方程轉換為可以更容易求解的等價方程,意味著我們直接從方程求解。
-
迭代方法 :迭代或間接方法,從猜測解開始,然後重複細化解決方案,直到達到某個收斂標準。迭代方法通常比直接方法效率低,因為需要大量操作。示例 - 雅可比迭代法,高斯 - 密度迭代法。
在 C-中實施
//Implementation of Jacobi's Method
void JacobisMethod(int n, double x[n], double b[n], double a[n][n]){
double Nx[n]; //modified form of variables
int rootFound=0; //flag
int i, j;
while(!rootFound){
for(i=0; i<n; i++){ //calculation
Nx[i]=b[i];
for(j=0; j<n; j++){
if(i!=j) Nx[i] = Nx[i]-a[i][j]*x[j];
}
Nx[i] = Nx[i] / a[i][i];
}
rootFound=1; //verification
for(i=0; i<n; i++){
if(!( (Nx[i]-x[i])/x[i] > -0.000001 && (Nx[i]-x[i])/x[i] < 0.000001 )){
rootFound=0;
break;
}
}
for(i=0; i<n; i++){ //evaluation
x[i]=Nx[i];
}
}
return ;
}
//Implementation of Gauss-Seidal Method
void GaussSeidalMethod(int n, double x[n], double b[n], double a[n][n]){
double Nx[n]; //modified form of variables
int rootFound=0; //flag
int i, j;
for(i=0; i<n; i++){ //initialization
Nx[i]=x[i];
}
while(!rootFound){
for(i=0; i<n; i++){ //calculation
Nx[i]=b[i];
for(j=0; j<n; j++){
if(i!=j) Nx[i] = Nx[i]-a[i][j]*Nx[j];
}
Nx[i] = Nx[i] / a[i][i];
}
rootFound=1; //verification
for(i=0; i<n; i++){
if(!( (Nx[i]-x[i])/x[i] > -0.000001 && (Nx[i]-x[i])/x[i] < 0.000001 )){
rootFound=0;
break;
}
}
for(i=0; i<n; i++){ //evaluation
x[i]=Nx[i];
}
}
return ;
}
//Print array with comma separation
void print(int n, double x[n]){
int i;
for(i=0; i<n; i++){
printf("%lf, ", x[i]);
}
printf("\n\n");
return ;
}
int main(){
//equation initialization
int n=3; //number of variables
double x[n]; //variables
double b[n], //constants
a[n][n]; //arguments
//assign values
a[0][0]=8; a[0][1]=2; a[0][2]=-2; b[0]=8; //8x₁+2x₂-2x₃+8=0
a[1][0]=1; a[1][1]=-8; a[1][2]=3; b[1]=-4; //x₁-8x₂+3x₃-4=0
a[2][0]=2; a[2][1]=1; a[2][2]=9; b[2]=12; //2x₁+x₂+9x₃+12=0
int i;
for(i=0; i<n; i++){ //initialization
x[i]=0;
}
JacobisMethod(n, x, b, a);
print(n, x);
for(i=0; i<n; i++){ //initialization
x[i]=0;
}
GaussSeidalMethod(n, x, b, a);
print(n, x);
return 0;
}