一、实验目的
1.借助矩阵按模最大特征值,判断解方程组的Jacobi迭代法所得迭代序列的敛散性。
2.会在Jacobi迭代法所得迭代序列收敛时,用修改后的Gauss-Seidel迭代法。
3.会逐次超松驰迭代法。
二、实验原理
三、实验程序
四、实验内容
用上面前二种方法求解如下4元线性方程组的近似解,所选方程组尽可能可以用多种方法求得收敛解。
注:要注意判断迭代法收敛性,方法之一就是用程序求矩阵的按模最大特征值。
五、java源码
1 package shuzhifenxi; 2 3 4 5 import java.util.Scanner; 6 public class J { 7 static int n = 4; 8 public static void main(String[] args) { 9 float[][] A = { { 10, -1, 2, 0 }, { -1, 11, -1,3 }, 10 { 2, -1, 10, -1 }, { 0, 3, -1, 8 } }; 11 float[] B = { 6, 25, -11, 15 }; 12 float e, m, temp, t; 13 float y[] = { 0.0f, 0.0f, 0.0f, 0.0f }, 14 x0[] = { 0.0f,0.0f, 0.0f, 0.0f }, 15 x[] = { 0.0f, 0.0f, 0.0f, 0.0f }; 16 int N, i, j, k,sum1,sum2; 17 System.out.println("输入要求的精度e="); 18 Scanner scan = new Scanner(System.in); 19 e = scan.nextFloat(); 20 System.out.println("最大迭代次数N="); 21 N = scan.nextInt(); 22 for (i = 0; i < n; i++) { 23 System.out.println("x0" + "[" + i + "]=" + x0[i]); 24 } 25 System.out.println("*************************************"); 26 System.out.println("以下是Jacobi迭代过程"); 27 System.out.println("*************************************"); 28 for (k = 0; k < N; k++) { 29 m = 0; 30 for (i = 0; i < n; i++) { 31 x[i] = B[i]; 32 for (j = 0; j < n; j++) 33 if (j != i) { 34 x[i] = x[i] - A[i][j] * x0[j]; 35 } 36 x[i] = x[i] / A[i][i]; 37 System.out.println("x[]" + x[i]); 38 temp = Math.abs(x[i] - x0[i]); 39 System.out.println("temp" + temp); 40 if (temp > m) 41 m = temp; 42 } 43 System.out.print(k + 1 + "次迭代:"); 44 45 46 for (int i1 = 0; i1 < n; i1++) { 47 System.out.println("x" + "[" + i1 + "]=" + x[i1]); 48 x0[i1] = x[i1]; 49 } 50 if (m < e) { 51 sum1=k+1; 52 System.out.println("Jacobi迭代结束"); 53 System.out.println("一共迭代了"+sum1+"次"); 54 break; 55 } 56 57 } 58 59 if (k > N) 60 System.out.println("第" + k + "次迭代未找出满足精度的解 发散"); 61 System.out.println("\n"); 62 System.out.println("*************************************"); 63 System.out.println("以下是Gauss-Seidel迭代"); 64 System.out.println("*************************************"); 65 for (k = 0; k < N; k++) { 66 m = 0; 67 for (i = 0; i < n; i++) { 68 t=y[i]; 69 y[i] = B[i]; 70 for (j = 0; j < n; j++) 71 if (j != i) { 72 y[i] = y[i] - A[i][j] * y[j]; 73 } 74 y[i] =y[i] / A[i][i]; 75 temp = Math.abs(y[i] - t); 76 System.out.println("temp" + temp); 77 if (temp > m) 78 m = temp; 79 } 80 System.out.print(k + 1 + "次迭代:"); 81 for (int i1 = 0; i1 < n; i1++) { 82 System.out.println("x" + "[" + i1 + "]=" + y[i1]); 83 } 84 if (m < e) { 85 sum2=k+1; 86 System.out.println("Gauss-Seidel迭代结束"); 87 System.out.println("一共迭代了"+sum2+ "次"); 88 break; 89 } 90 91 if (k > N) 92 System.out.println("第" + k + "次迭代未找出满足精度的解 发散"); 93 94 } 95 96 97 } 98 }
运行结果:
Jacobi迭代:
Gauss-Seidel迭代