Advertisement
nate23nate23

HW 6 attempt 2

Oct 2nd, 2015
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. /**
  2.  * Nate Wheeler
  3.  * compsci 220
  4.  * Hw 6
  5.  * Email: nrwheel@student.stcc.edu
  6.  *
  7.  */
  8.  
  9. import java.util.Arrays;
  10. import java.util.Scanner;
  11.  
  12. public class Hw6 {
  13.  
  14.     public static void main(String[] args) {
  15.         // TODO Auto-generated method stub
  16.         System.out.println("Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: ");
  17.         Scanner input = new Scanner(System.in);
  18.         double[][] matrix = new double[3][3];
  19.         for (int i = 0; i < matrix.length; i++) {
  20.             for (int j = 0; j < matrix[i].length; j++) {
  21.                 matrix[i][j] = input.nextDouble();
  22.             }
  23.         }
  24.         System.out.println("");
  25.         System.out.println(Arrays.deepToString(matrix));
  26.         if (inverse(matrix) == null)
  27.             System.out.println("No inverse matrix");
  28.         else
  29.             System.out.println(Arrays.deepToString(inverse(matrix)));
  30.  
  31.     }
  32.  
  33.     public static double[][] inverse(double[][] a) {
  34.         double determinate;
  35.         determinate = a[0][0] * a[1][1] * a[2][2] + a[2][1] * a[0][1] * a[1][2] + a[0][2] * a[1][0] * a[2][0]
  36.                 - a[0][2] * a[1][1] * a[2][0] - a[0][0] * a[1][2] * a[2][1] - a[2][2] * a[1][0] * a[0][1];
  37.         if (determinate == 0) {
  38.             return null;
  39.         }
  40.         // first row
  41.         a[0][0] = a[1][1] * a[2][2] - a[1][2] * a[2][1];
  42.         a[0][1] = a[0][2] * a[2][1] - a[0][1] * a[2][2];
  43.         a[0][2] = a[0][1] * a[1][2] - a[0][2] * a[1][1];
  44.         // second row
  45.         a[1][0] = a[1][2] * a[2][0] - a[1][0] * a[2][2];
  46.         a[1][1] = a[0][0] * a[2][2] - a[0][2] * a[2][0];
  47.         a[1][2] = a[0][2] * a[1][0] - a[0][0] * a[1][0];
  48.         // third row
  49.         a[2][0] = a[1][0] * a[2][1] - a[1][1] * a[2][0];
  50.         a[2][1] = a[0][1] * a[2][0] - a[0][0] * a[2][1];
  51.         a[2][1] = a[0][0] * a[1][1] - a[0][1] * a[1][0];
  52.  
  53.         for (int i = 0; i < a.length; i++) {
  54.             for (int j = 0; j < a[i].length; j++) {
  55.                 a[i][j] = 1 / determinate * a[i][j];
  56.             }
  57.         }
  58.         return a;
  59.     }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement