数值方法Gauss顺序消元法解线性方程组

数值方法Gauss顺序消元法解线性方程组_第1张图片
数值方法Gauss顺序消元法解线性方程组_第2张图片

import java.util.Scanner;

public class Gauss {
    static final int MAXN=  20;
    static double a[][]=new double[MAXN][MAXN];
    static double b[][]=new double[2][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 i = 0; i < num; i++) {//初始化计数数列
            b[0][i] = i;
            b[1][i] = 0;
        }
        for (int j = 0; j < num-1; j++)
        {
            dengjia(j);

        }

        for (int i = num - 1; i >= 0; i--) {
            jiefangcheng(i);
        }
        for (int j = 0; j < num; j++) {
            System.out.println("x"+(j+1)+"="+b[1][j]);
        }
    }
    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 jiefangcheng(int ii) {//解方程
        for (int j = ii + 1; j < num; j++)
        {
            a[ii][num] -= a[ii][j] * b[1][j];
        }
        b[1][ii] = a[ii][num] / a[ii][ii];

    }
}

数值方法Gauss顺序消元法解线性方程组_第3张图片

你可能感兴趣的:(数值计算方法)