数值方法高斯若当消元法解线性方程组
程序员文章站
2022-07-05 17:01:43
...
import java.util.Scanner;
public class Gauss {
static final int MAXN= 20;
static double a[][]=new double[MAXN][MAXN];
static int num;
public static void main(String[] args) {
System.out.println("输入未知数个数:");
Scanner sc=new Scanner(System.in);
num=sc.nextInt();
System.out.println("输入用矩阵表示的线性方程组:");
for (int i = 0; i < num; i++) {//输入方程组
for (int j = 0; j <= num; j++) {
a[i][j]=sc.nextDouble();
}
}
for (int j = 0; j < num-1; j++)
{
guiyi(j);
dengjia(j);
guiling(j+1);
}
guiyi(num-1);
for(int i=0;i<num;i++)
{
System.out.println("x"+i+"="+a[i][num]);
}
}
static void dengjia(int jj) {//把原矩阵转化成三角形的
for (int i = jj + 1; i < num; i++) {
double k = a[i][jj]/ a[jj][jj];
for (int j = jj; j <= num; j++) {
a[i][j] = a[i][j] - a[jj][j] * k;
}
}
}
static void guiyi(int jj){//使akk变为1
for(int i=num;i>=0;i--){
a[jj][i]=a[jj][i]/a[jj][jj];
}
}
static void guiling(int jj){//使其他值变为0
for(int i=0;i<jj;i++){
double k=(-a[i][jj])/a[jj][jj];
for(int j=jj;j<=num;j++){
a[i][j]+=a[jj][j]*k;
}
}
}
}