数值方法完全主元素消元法解线性方程组
程序员文章站
2022-07-05 16:58:19
...
原题排序成这样就行了
本程序是排成这样,懒得改了,差不多就行,嘿嘿
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;
static int x_max;
static int y_max;
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; j++) {
a[num][j] = j;
}
for (int j = 0; j < num - 1; j++) {
findMax(j);
sort1(j);
findMax(j);
sort2(j);
dengjia(j);
}
for (int i = num - 1; i >= 0; i--) {
jiefangcheng(i);
}
for (int j = 0; j < num; j++) {
System.out.println("x" + (a[num][j] + 1) + "=" + b[1][j]);
}
}
static void sort1(int jj) {//行排序
for (int j = jj; j < num - 1; j++) {
for (int k = jj; k < num - 1; k++) {
if (Math.abs(a[k][x_max]) < Math.abs(a[k + 1][x_max])) {
for (int i = jj; i <= num; i++) {
double temp = a[k][i];
a[k][i] = a[k + 1][i];
a[k + 1][i] = temp;
}
}
}
}
}
static void sort2(int jj) {//列排序
for (int j = jj; j < num - 1; j++) {
for (int k = jj; k < num - 1; k++) {
if (Math.abs(a[y_max][k]) < Math.abs(a[y_max][k+1])) {
for (int i = 0; i <= num; i++) {
double temp = a[i][k];
a[i][k] = a[i][k + 1];
a[i][k + 1] = temp;
}
}
}
}
}
static void findMax(int jj) {
double max = 0;
for (int i = jj; i < num; i++) {
for (int j = jj; j < num; j++) {
if (Math.abs(a[i][j]) > Math.abs(max)) {
max = a[i][j];
y_max = i;
x_max = 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];
}
}
上一篇: Python编程学习3:Python 对象引用和 del 删除引用
下一篇: 软连接和硬链接的区别