数值分析中的高斯—塞德尔迭代算法

本例是用java语言实现的,适合于学习数值分析课程的同学借鉴;

package c;

import java.util.Scanner;

public class Demo {

    public static void main(String []args)
    {
        boolean flag = true;
         int N,n,t = 0;    //N迭代次数,n指是x的下标
         double e = 0;
         double [][] X = new double[30][30];
         double b[] = new double[30];
         double a[][] = new double[30][30];

         Scanner in = new Scanner(System.in);

         System.out.print("请输入初始值x的个数:");
         n = in.nextInt();
         System.out.print("请输入迭代次数:");
         N = in.nextInt();
         System.out.print("请输入精度值(0.00....1)");
         e = in.nextDouble();

         for(int i = 1;i<=n;i++)
         {
             System.out.print("b["+i+"]=");
             b[i] = in.nextDouble();
         }

         System.out.println("请输入x的初始值");
         for(int i = 1;i<=n;i++)
         {
             System.out.print("X["+i+"][0]=");
             X[i][0] = in.nextDouble();
         }


         System.out.println("请输入对应的a值");
         for(int i = 1;i<=n;i++)
             for(int j = 1;j<=n;j++)
             {
                System.out.print("a["+i+"]["+j+"] = ");
                a[i][j] = in.nextDouble();
             }


         while(t<N)
         {
             for(int i = 1;i<=n;i++)
             {
                 double f1 = 0;
                 for(int j = 1;j<=n;j++)
                 {
                     if(j!=i) f1 += a[i][j]*X[j][t];
                 }
                 X[i][t+1] = (b[i]-f1)/a[i][i];

                 double f2 = 0;
                 double f3 = 0;
                 for(int m = 1;m<=i-1;m++)
                 {
                     f2 += a[i][m]*X[m][t+1];
                 }

                 for(int m = i+1;m<=n;m++)
                 {
                     f3 += a[i][m]*X[m][t];
                 }
                 X[i][t+1] = (b[i]-f2-f3)/a[i][i];
                 System.out.printf("X["+i+"]["+(t+1)+"] = %.5f",X[i][t+1]);
                 System.out.print(" ");
             }  
             System.out.println();

             for(int i = 1;i<=n;i++)
             {
                 if(Math.abs(X[i][t+1]-X[i][t])<e)
                 {
                     for(int j = 1;j<=n;j++)
                     System.out.printf("X["+j+"]["+(t+1)+"] = %.5f",X[j][t+1]);
                     flag = false;
                     break;
                 } 
             }
             if(flag == true)
                  t++;
             else
                 break;
         }   //end of while
         if(t==N)
             System.out.println("迭代次数不够或失败,未达到指定精度!");
    }
}
全部评论

相关推荐

AI牛可乐:哇,听起来你遇到了什么挑战呢!🐮牛可乐在这里,虽然小,但是勇敢又聪明,想听听你的具体情况哦!如果你愿意的话,可以点击我的头像给我私信,我们可以一起想办法应对挑战,好不好呀?🌟🎉
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务