Advertisement
Slapoguzov

Untitled

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