数值方法LU法解线性方程组
程序员文章站
2022-07-05 17:01:01
...
import java.util.Scanner;
public class Gauss {
final static int MAXN = 20;
//static double A[][]=new double[MAXN][MAXN];
static double L[][] = new double[MAXN][MAXN];
static double U[][] = new double[MAXN][MAXN];
// static double x[] = new double[MAXN];
static double y[] = new double[MAXN];
//static double temp[] = new double[MAXN];
static int num;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入未知数个数:");
num = sc.nextInt();
System.out.println("以矩阵的形式输入方程组:");
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
U[i][j] = sc.nextDouble();
L[i][j]=0;
}
y[i] = sc.nextDouble();
}
// for(int i=0;i<num;i++){
// System.out.println(y[i]+" ");
// }
for (int i = 0; i < num - 1; i++) {
handlL(i);
handlU(i);
}
L[num-1][num-1]=1;
// for(int i=0;i<num;i++){
// for(int j=0;j<num;j++){
// System.out.print(U[i][j]+" ");
// }
// System.out.println();
// }
for(int i=0;i<num;i++){
jiefangchengL(i);
}
for(int i=num-1;i>=0;i--){
jiefangchengU(i);
}
for(int i=0;i<num;i++){
System.out.println("x"+i+"="+y[i]+" ");
}
}
static void jiefangchengL(int ii){
for(int i=0;i<ii;i++){
y[ii]-=L[ii][i]*y[i];
}
y[ii]=y[ii]/L[ii][ii];//可有可无
}static void jiefangchengU(int ii){
for(int i=num-1;i>ii;i--){
y[ii]-=U[ii][i]*y[i];
}
y[ii]=y[ii]/U[ii][ii];
}
static void handlL(int ii) {
for (int i = num - 1; i >= ii; i--) {
L[i][ii] =U[i][ii]/ U[ii][ii];
}
}
static void handlU(int ii) {
for (int i = ii + 1; i < num; i++) {
double k = U[i][ii] / U[ii][ii];
for (int j = 0; j < num; j++) {
U[i][j] -= U[ii][j] * k;
}
}
}
}
上一篇: 机器人和外科医生哪个做手术更牛