請問大家,這一個程式碼要怎麼編寫使用高斯消去法計算出矩陣Ax=b?
這題有人替他女朋友寫好了
可以拿去修改即可
執行結果
Please solve a linear system Ax=b and print x via function print_vector
A =
0.000000 1.000000 2.000000 3.000000 4.000000 5.000000
1.000000 2.000000 1.000000 2.000000 3.000000 4.000000
2.000000 3.000000 4.000000 1.000000 2.000000 3.000000
3.000000 4.000000 5.000000 6.000000 1.000000 2.000000
4.000000 5.000000 6.000000 7.000000 8.000000 1.000000
5.000000 6.000000 7.000000 8.000000 9.000000 10.000000
b =
0.000000
2.000000
4.000000
6.000000
8.000000
10.000000
x =
-inf
-2.674479
-0.317708
0.520833
0.875000
1.000000
程式碼
#include <stdlib.h>
#include <stdio.h>
#define M_size 6
double A[M_size][M_size];
double b[M_size];
double x[M_size];
int i,j,k;
float Aik;
float S;
void assignValue(double a[][M_size], double b[M_size]){
//assign value to matrix
for(int i=0; i<M_size; i++){
for (int j=0; j<M_size; j++){
if (i<j){
a[i][j] = j-i;
} else {
a[i][j] = i+j;
}
}
}
//asign value to vector
for(int i=0; i<M_size; i++){
b[i] = 2*i;
}
}
void print_Marix(double a[][M_size]){
for (int i=0; i<M_size; i++){
for(int j=0; j<M_size; j++){
printf("%f\t", a[i][j]);
}
printf("\n");
}
}
void print_vector(double v[M_size]){
for (int i=0; i<M_size; i++){
printf("%f\t", v[i]);
printf("\n");
}
}
void Gaussian_step_1() {
for(k=0;k<M_size-1;k++) {
if(!A[k][k])
return;
for(i=k+1;i<M_size;i++) {
Aik=A[i][k]/A[k][k];
for(j=k;j<M_size;j++) {
A[i][j]=A[i][j]-Aik*A[k][j];
}
b[i]=b[i]-Aik*b[k];
}
}
}
void Gaussian_step_2() {
x[M_size-1]=b[M_size-1]/A[M_size-1][M_size-1];
for(k=M_size-2;k>=0;k--)
{
S=b[k];
for(j=k+1;j<M_size;j++)
{
S=S-A[k][j]*x[j];
}
x[k]=S/A[k][k];
} //回代
}
int main(){
assignValue(A, b);
printf("Please solve a linear system Ax=b and print x via function print_vector\n");
Gaussian_step_1();
Gaussian_step_2();
printf("A = \n");
print_Marix(A);
printf("b = \n");
print_vector(b);
printf("x = \n");
print_vector(x);
return 0;
}