python如何给追赶法编写程序 10
2018-01-06
追赶法是解决稀疏矩阵的 一种方法,但应该满足对角占优,否则不能进行计算,下面是程序,语言为java
[java] view plain copy
import java.util.Scanner;
/**
* Created by q on 2017/11/30.
*/
public class ChasingMethod {
private int num; //numb比矩阵的阶大一,不用下标是0的空间
private double a[];
private double b[];
private double c[];
private double y[];
public ChasingMethod(int num, double[] a, double[] b, double[] c, double[] y) {
this.num = num;
this.a = a;
this.b = b;
this.c = c;
this.y = y;
}
public boolean check(){ //判断是否对角占优
if(Math.abs(b[1])<Math.abs(c[1])) return false;
for(int i = 2;i <num ;i++){
double temp = Math.abs(a[i])+ Math.abs(c[i]);
if(Math.abs(b[i])<temp){
return false;
}
}
if(Math.abs(b[num])<Math.abs(a[num])) return false;
return true;
}
public void calB(){
c[1] = c[1]*1.0/b[1];
for(int i = 2;i <num ;i++){
c[i] = c[i] *1.0/ (b[i] - a[i]* c[i-1]); //Ci = Ci/( bi-aiβi-1)
}
}
public void calY(){
y[1] = y[1]*1.0 / b[1];
for(int i = 2;i <= num ;i++){
y[i] = (y[i] - a[i]*y[i-1])*1.0/ (b[i] - a[i]* c[i-1]);
//fi = (fi -aiyi-1)/ ( bi-aiβi-1) (yi-1已存放在fi-1 ,βi-1已存入Ci-1)
}
}
public void calX(){
for(int i = num-1;i>0;i--){
y[i] = y[i] - c[i]* y[i+1];//fi = fi -Ci fi+1
}
}
public void print(){
for(int i = 1;i<=num;i++){
System.out.println(y[i]);
}
}
public static void main(String [] args){
Scanner scanner = new Scanner(System.in);
int n;
System.out.println("请输入X的个数");
n = scanner.nextInt();
double a[] = new double[n+1];
double b[] = new double[n+1];
double c[] = new double[n+1];
double y[] = new double[n+1];
System.out.println("请输入A数组");
for(int i=2;i<=n;i++){
a[i] = scanner.nextDouble();
}
System.out.println("请输入B数组");
for(int i=1;i<=n;i++){
b[i] = scanner.nextDouble();
}
System.out.println("请输入C数组");
for(int i=1;i<=n-1;i++){
c[i] = scanner.nextDouble();
}System.out.println("请输入Y数组");
for(int i=1;i<=n;i++){
y[i] = scanner.nextDouble();
}
ChasingMethod method = new ChasingMethod(n,a,b,c,y);
if(!method.check()){
System.out.println("不满足对焦占优的条件,程序退出");
return;
}
method.calB();
method.calY();
method.calX();
method.print();
}
}