Advertisement
Slapoguzov

MethodGaussa

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