Advertisement
Slapoguzov

MethodGaussa2

Sep 20th, 2014
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.79 KB | None | 0 0
  1. package vm_lab1_methodgaussa;
  2.  
  3. import java.util.Arrays;
  4. import java.io.*;
  5. /**
  6.  *
  7.  * @author Alex Slapoguzov
  8.  */
  9.  
  10. class MethodGaussa {
  11.    
  12.     double[][] A;          //матрица коэффициентов при неизвестных
  13.     double[] X;            //матрица-столбец неизвестных
  14.     double[] B;            //матрица-столбец свободных членов
  15.    
  16.     int n;                //количество уравнений
  17.     int m;                //количество неизвестных
  18.    
  19.    
  20.     public MethodGaussa(double[][] A, double[] X, double[] B)
  21.     {
  22.        this.A = A.clone();
  23.        this.X = X;
  24.        this.B = B.clone();
  25.        
  26.        
  27.        this.n = A.length;
  28.        this.m = A[0].length;
  29.        if(n>20) throw new  ArithmeticException("Чило строк должно быть не больше 20");
  30.     }
  31.    
  32.     public void toTriangularMatrix() {
  33.        
  34.        for(int i = 0; i < m; i++)
  35.        {
  36.            for(int k = i; k < n-1; k++)
  37.            {
  38.              if(0 != A[i][i])
  39.              {
  40.                  double mn = A[k+1][i]/A[i][i];
  41.                  if(mn == 0) continue;
  42.                  for(int j=0; j < m; j++)
  43.                  {
  44.                      A[i][j] *= mn;    
  45.                      A[k+1][j] -= A[i][j];
  46.                      
  47.                  }
  48.                  A[k+1][i]=0;
  49.                  B[i] *= mn;
  50.                  B[k+1] -= B[i];
  51.              } else if( i != n-1) {
  52.                  for(int j=0; j < m; j++)
  53.                  {
  54.                      double temp = A[i][j];
  55.                      A[i][j] = A[i+1][j];
  56.                      A[i+1][j] = temp;
  57.                      
  58.                  }
  59.                  double temp = B[i];
  60.                  B[i] = B[i+1];
  61.                  B[i+1] = temp;
  62.                  i--;
  63.              }
  64.            }
  65.        }
  66.     }
  67.    
  68.     public double getDet(double[][] matrix) throws ArithmeticException {
  69.  
  70.       double result = 0;
  71.  
  72.       // для матрицы из одного столбца и строчки
  73.       if(matrix.length == 1) {
  74.         result = matrix[0][0];
  75.         if(result == 0) throw new ArithmeticException("Определитель равен 0. Система не имеет решений");
  76.         return result;
  77.       }
  78.  
  79.       // для матрицы 2х2
  80.       if(matrix.length == 2) {
  81.         result = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
  82.         if(result == 0) throw new ArithmeticException("Определитель равен 0. Система не имеет решений");
  83.         return result;
  84.       }
  85.  
  86.       for(int i = 0; i < matrix[0].length; i++)
  87.           {
  88.         double temp[][] = new double[matrix.length - 1][matrix[0].length - 1];
  89.  
  90.  
  91.         for(int j = 1; j < matrix.length; j++) {
  92.  
  93.           System.arraycopy(matrix[j], 0, temp[j-1], 0, i);
  94.           System.arraycopy(matrix[j], i+1, temp[j-1], i, matrix[0].length-i-1);
  95.         }
  96.  
  97.  
  98.         result += matrix[0][i] * Math.pow(-1, i) * getDet(temp);
  99.       }
  100.       if(result == 0) throw new ArithmeticException("Определитель равен 0. Система не имеет решений");
  101.       return result;
  102.     }
  103.    
  104.     public double[] solve() throws ArithmeticException{
  105.        
  106.         B[m-1] /= A[n-1][m-1];
  107.         A[n-1][m-1] /= A[n-1][m-1];
  108.        
  109.         for(int i = m-2; i>=0; i--)
  110.         {
  111.             if(A[i][i] == 0) { throw new ArithmeticException("Система не имеет решений"); }
  112.             for(int j = i; j >= 0; j--)
  113.             {
  114.                 B[j] -= (B[i+1]*A[j][i+1]);
  115.                 A[j][i+1] = 0.0;
  116.             }
  117.             B[i] /=A[i][i];
  118.            
  119.             A[i][i] = 1;
  120.         }
  121.         X = B;
  122.     return this.X;
  123.     }
  124.    
  125.  
  126. }
  127. public class VM_Lab1_MethodGaussa {
  128.  
  129.     static double[][] A1;
  130.     static double[] B;
  131.    
  132.     public static double[][] copyArr(double[][] A)
  133.     {
  134.         double[][] N = new double[A.length][];
  135.         for(int i=0; i< A.length; i++)
  136.         {
  137.             N[i] = Arrays.copyOf(A[i], A[i].length);
  138.         }
  139.         return N;
  140.     }
  141.    
  142.   public static double roundResult (double d, int precise) {
  143.  
  144.    precise = 10^precise;
  145.    d = d*precise;
  146.    int i = (int) Math.round(d);
  147.    return (double) i/precise;
  148.  
  149. }
  150.    
  151.     public static void main(String[] args) throws FileNotFoundException, IOException {
  152.        
  153.         try {
  154.            
  155.        
  156.         System.out.println("Введите путь к файлу или введите n для ввода в консоли: ");
  157.         BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
  158.  
  159.         String str = stdin.readLine();
  160.        
  161.         if(str.equals("n"))
  162.         {
  163.             String line = null;
  164.             String text = "";
  165.             System.out.println("Введите расширенную матрицу уравнения: ");
  166.             line = stdin.readLine();
  167.             while (!line.equals("q")) {
  168.            
  169.             text += line +"\n";
  170.             line = stdin.readLine();
  171.         }
  172.             convertStringToMat( text);
  173.         }
  174.         else
  175.         {
  176.         readFile(str);
  177.         }
  178.         double[] X = {1.0,1.0,1.0};
  179.  
  180.        
  181.        
  182.         MethodGaussa My = new MethodGaussa(copyArr(A1),X,B);
  183.        
  184.         //Выводим определитель
  185.         try {
  186.         double Det  =  My.getDet(My.A);
  187.         System.out.println("Определитель матрицы: " + Det);
  188.         }
  189.         catch(ArithmeticException e)
  190.         {
  191.             System.out.println(e.getMessage());
  192.             System.exit(0);
  193.         }
  194.        
  195.         //Выводим треугольную матрицу
  196.         My.toTriangularMatrix();
  197.         System.out.println("Треугольная матрица:");
  198.         for(int i=0; i< My.A.length; i++)
  199.         {
  200.             double [] r = My.A[i];
  201.             for(double n: r)
  202.             {
  203.                 System.out.print(roundResult(n,2)+"\t");
  204.             }
  205.            
  206.             System.out.print(roundResult(B[i],2));
  207.             System.out.println();
  208.         }
  209.        
  210.         //Выводим неизвестные
  211.         System.out.println("Решение системы:");
  212.             try {
  213.             X = My.solve();
  214.             }
  215.             catch(ArithmeticException e)
  216.             {
  217.                 System.out.println(e.getMessage());
  218.             }
  219.            
  220.             for(double x : X)
  221.             {
  222.                 System.out.println(roundResult(x,2));
  223.             }
  224.            
  225.             //Выводим столбец невязок
  226.             System.out.println("Столбец невязок:");
  227.             for(int i = 0; i < X.length; i++)
  228.             {
  229.                double n = 0;
  230.                for(int j = 0; j < X.length; j++)
  231.                {
  232.                    n += (X[j]*A1[i][j]);
  233.                }
  234.                System.out.println(B[i]-n);
  235.             }  
  236.         }
  237.         catch(NumberFormatException e)
  238.         {
  239.             System.out.println("Некорректный ввод");
  240.             System.exit(0);
  241.         }
  242.         catch(ArithmeticException e)
  243.         {
  244.             System.out.println(e);
  245.             System.exit(0);
  246.         }
  247.     }
  248.    
  249.     public static void convertStringToMat(String str) throws ArithmeticException
  250.     {
  251.         String[] lines = str.split("\\r?\\n");
  252.         B = new double[lines.length];
  253.         A1 = new double[lines.length][lines.length];
  254.         for(int i = 0; i < lines.length; i++)
  255.         {
  256.             String[] ch = lines[i].split(" ");
  257.             if(lines.length != ch.length-1) throw new ArithmeticException("Чило уравнений должно совпадать с числом переменных");
  258.             for(int k=0;  k < ch.length; k++)
  259.             {
  260.                 if( k < lines.length) {
  261.                     A1[i][k] = Double.parseDouble(ch[k].replaceAll("", ""));
  262.                 }
  263.                 else {
  264.                     B[i] = Double.parseDouble(ch[k].replaceAll("", ""));
  265.                 }
  266.             }
  267.         }
  268.     }
  269.     public static void readFile(String path)  throws FileNotFoundException, IOException
  270.     {
  271.         File file = new File( path );
  272.  
  273.         BufferedReader br = new BufferedReader (
  274.             new InputStreamReader(
  275.                 new FileInputStream( file ), "UTF-8"
  276.             )
  277.         );
  278.        
  279.         String line = null;
  280.         String text = "";
  281.         while ((line = br.readLine()) != null) {
  282.             //variable line does NOT have new-line-character at the end
  283.             text += line +"\n";
  284.         }
  285.         br.close();
  286.         convertStringToMat(text);
  287.        
  288.     }
  289. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement