public class yakebi {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
float[][] a = { { 10, -2, -2 }, { -2, 10, -1 }, { -1, -2, 3 } };
float[] b = { 1, (float) 0.5, 1 };
float[] x = new float[3];
float[] x0 = new float[3];
float[] x1 = new float[3];
float[] x2 = new float[3];
yakebi C=new yakebi();
System.out.println("方程组矩阵为:");
C.outPut2D(a);
System.out.println("方程组的右边为:");
C.output1D(b);
System.out.println("方程组的初始解为:");
C.output1D(x);
System.out.println("雅克比方法迭代后结果为:");
C.Jacobi(a, b, x, x0);
System.out.println("方程组的解为:");
C.output1D(x);
System.out.println("高斯-赛德尔方法迭代后结果为:");
C.GS(a, b, x1, x2);
System.out.println("方程组的解为:");
C.output1D(x1);
}
public void outPut2D(float a[][]){//用于输出方程组的系数矩阵
for(int i=0;i<3;i++){
for(int j=0;j<3;j++)
System.out.print(" "+a[i][j]);
System.out.println();
}
}
public void output1D(float b[]){//用于输出方程组的右边,方程组的初始解,和迭代后的结果
for(int i=0;i<3;i++)
System.out.println(" "+b[i]);
}
public void Jacobi(float a[][], float b[], float x[], float x0[]) {//雅克比迭代方法
int count=0;
do {
for (int i = 0; i < 3; i++)
x0[i] = x[i];
x[0] = (b[0] - a[0][1] * x0[1] - a[0][2] * x0[2])/10;//a[1][1]=10
x[1] = (b[1] - a[1][0] * x0[0] - a[1][2] * x0[2])/10;//a[2][2]=10
x[2] = (b[2] - a[2][0] * x0[0] - a[2][1] * x0[1])/3;//a[3][3]=3
count++;
} while (fanshu(x, x0));
System.out.println("迭代的次数为:"+count);
}
public void GS(float a[][], float b[], float x[], float x0[]) {//高斯赛德尔迭代
int count=0;
do {
for (int i = 0; i < 3; i++)
x0[i] = x[i];
x[0] = (b[0] - a[0][1] * x[1] - a[0][2] * x[2])/10;//a[1][1]=10
x[1] = (b[1] - a[1][0] * x[0] - a[1][2] * x[2])/10;//a[2][2]=10
x[2] = (b[2] - a[2][0] * x[0] - a[2][1] * x[1])/3;//a[3][3]=3
count++;
} while (fanshu(x, x0));
System.out.println("迭代的次数为:"+count);
}
public boolean fanshu(float x[], float x0[]) {//误差||r||1-范数
float[] s = new float[3];
float w;
for (int i = 0; i < 3; i++)
s[i] = x[i] - x0[i];
w = s[0];
for (int j = 0; j < 2; j++) {
if (Math.abs(s[j]) <= Math.abs(s[j + 1]))
w = Math.abs(s[j + 1]);//当误差的1-范数<精度0.00000000001迭代结束
}
if (w < 0.00000000001)
return false;
else
return true;
}
}
评论0