Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package vm_lab1_methodgaussa;
- import java.util.Arrays;
- import java.io.*;
- /**
- *
- * @author Alex Slapoguzov
- */
- class MethodGaussa {
- double[][] A; //матрица коэффициентов при неизвестных
- double[] X; //матрица-столбец неизвестных
- double[] B; //матрица-столбец свободных членов
- int n; //количество уравнений
- int m; //количество неизвестных
- public MethodGaussa(double[][] A, double[] X, double[] B)
- {
- this.A = A.clone();
- this.X = X;
- this.B = B.clone();
- this.n = A.length;
- this.m = A[0].length;
- if(n>20) throw new ArithmeticException("Чило строк должно быть не больше 20");
- }
- public void toTriangularMatrix() {
- for(int i = 0; i < m; i++)
- {
- for(int k = i; k < n-1; k++)
- {
- if(0 != A[i][i])
- {
- double mn = A[k+1][i]/A[i][i];
- if(mn == 0) continue;
- for(int j=0; j < m; j++)
- {
- A[i][j] *= mn;
- A[k+1][j] -= A[i][j];
- }
- A[k+1][i]=0;
- B[i] *= mn;
- B[k+1] -= B[i];
- } else if( i != n-1) {
- for(int j=0; j < m; j++)
- {
- double temp = A[i][j];
- A[i][j] = A[i+1][j];
- A[i+1][j] = temp;
- }
- double temp = B[i];
- B[i] = B[i+1];
- B[i+1] = temp;
- i--;
- }
- }
- }
- }
- public double getDet(double[][] matrix) throws ArithmeticException {
- double result = 0;
- // для матрицы из одного столбца и строчки
- if(matrix.length == 1) {
- result = matrix[0][0];
- if(result == 0) throw new ArithmeticException("Определитель равен 0. Система не имеет решений");
- return result;
- }
- // для матрицы 2х2
- if(matrix.length == 2) {
- result = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
- if(result == 0) throw new ArithmeticException("Определитель равен 0. Система не имеет решений");
- return result;
- }
- for(int i = 0; i < matrix[0].length; i++)
- {
- double temp[][] = new double[matrix.length - 1][matrix[0].length - 1];
- for(int j = 1; j < matrix.length; j++) {
- System.arraycopy(matrix[j], 0, temp[j-1], 0, i);
- System.arraycopy(matrix[j], i+1, temp[j-1], i, matrix[0].length-i-1);
- }
- result += matrix[0][i] * Math.pow(-1, i) * getDet(temp);
- }
- if(result == 0) throw new ArithmeticException("Определитель равен 0. Система не имеет решений");
- return result;
- }
- public double[] solve() throws ArithmeticException{
- B[m-1] /= A[n-1][m-1];
- A[n-1][m-1] /= A[n-1][m-1];
- for(int i = m-2; i>=0; i--)
- {
- if(A[i][i] == 0) { throw new ArithmeticException("Система не имеет решений"); }
- for(int j = i; j >= 0; j--)
- {
- B[j] -= (B[i+1]*A[j][i+1]);
- A[j][i+1] = 0.0;
- }
- B[i] /=A[i][i];
- A[i][i] = 1;
- }
- X = B;
- return this.X;
- }
- }
- public class VM_Lab1_MethodGaussa {
- static double[][] A1;
- static double[] B;
- public static double[][] copyArr(double[][] A)
- {
- double[][] N = new double[A.length][];
- for(int i=0; i< A.length; i++)
- {
- N[i] = Arrays.copyOf(A[i], A[i].length);
- }
- return N;
- }
- public static double roundResult (double d, int precise) {
- precise = 10^precise;
- d = d*precise;
- int i = (int) Math.round(d);
- return (double) i/precise;
- }
- public static void main(String[] args) throws FileNotFoundException, IOException {
- try {
- System.out.println("Введите путь к файлу или введите n для ввода в консоли: ");
- BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
- String str = stdin.readLine();
- if(str.equals("n"))
- {
- String line = null;
- String text = "";
- System.out.println("Введите расширенную матрицу уравнения: ");
- line = stdin.readLine();
- while (!line.equals("q")) {
- text += line +"\n";
- line = stdin.readLine();
- }
- convertStringToMat( text);
- }
- else
- {
- readFile(str);
- }
- double[] X = {1.0,1.0,1.0};
- MethodGaussa My = new MethodGaussa(copyArr(A1),X,B);
- //Выводим определитель
- try {
- double Det = My.getDet(My.A);
- System.out.println("Определитель матрицы: " + Det);
- }
- catch(ArithmeticException e)
- {
- System.out.println(e.getMessage());
- System.exit(0);
- }
- //Выводим треугольную матрицу
- My.toTriangularMatrix();
- System.out.println("Треугольная матрица:");
- for(int i=0; i< My.A.length; i++)
- {
- double [] r = My.A[i];
- for(double n: r)
- {
- System.out.print(roundResult(n,2)+"\t");
- }
- System.out.print(roundResult(B[i],2));
- System.out.println();
- }
- //Выводим неизвестные
- System.out.println("Решение системы:");
- try {
- X = My.solve();
- }
- catch(ArithmeticException e)
- {
- System.out.println(e.getMessage());
- }
- for(double x : X)
- {
- System.out.println(roundResult(x,2));
- }
- //Выводим столбец невязок
- System.out.println("Столбец невязок:");
- for(int i = 0; i < X.length; i++)
- {
- double n = 0;
- for(int j = 0; j < X.length; j++)
- {
- n += (X[j]*A1[i][j]);
- }
- System.out.println(B[i]-n);
- }
- }
- catch(NumberFormatException e)
- {
- System.out.println("Некорректный ввод");
- System.exit(0);
- }
- catch(ArithmeticException e)
- {
- System.out.println(e);
- System.exit(0);
- }
- }
- public static void convertStringToMat(String str) throws ArithmeticException
- {
- String[] lines = str.split("\\r?\\n");
- B = new double[lines.length];
- A1 = new double[lines.length][lines.length];
- for(int i = 0; i < lines.length; i++)
- {
- String[] ch = lines[i].split(" ");
- if(lines.length != ch.length-1) throw new ArithmeticException("Чило уравнений должно совпадать с числом переменных");
- for(int k=0; k < ch.length; k++)
- {
- if( k < lines.length) {
- A1[i][k] = Double.parseDouble(ch[k].replaceAll("", ""));
- }
- else {
- B[i] = Double.parseDouble(ch[k].replaceAll("", ""));
- }
- }
- }
- }
- public static void readFile(String path) throws FileNotFoundException, IOException
- {
- File file = new File( path );
- BufferedReader br = new BufferedReader (
- new InputStreamReader(
- new FileInputStream( file ), "UTF-8"
- )
- );
- String line = null;
- String text = "";
- while ((line = br.readLine()) != null) {
- //variable line does NOT have new-line-character at the end
- text += line +"\n";
- }
- br.close();
- convertStringToMat(text);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement