Advertisement
Slapoguzov

MethodGaussa3

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