fork download
  1. public class Main {
  2. public static void main(String[] args) {
  3.  
  4. double[][] A = {
  5. {2, 5},
  6. {-3, 1}
  7. };
  8.  
  9. double[] B = {11, -4};
  10.  
  11. System.out.println("Matrix A:");
  12. printMatrix(A);
  13.  
  14. System.out.println("\nVector B:");
  15. for (double v : B) System.out.println(v);
  16.  
  17. double detA = A[0][0] * A[1][1] - A[0][1] * A[1][0];
  18. System.out.println("\nDeterminant of A: " + detA);
  19.  
  20. if (detA == 0) {
  21. System.out.println("Matrix is singular. No unique solution.");
  22. return;
  23. }
  24.  
  25. double detA1 = B[0] * A[1][1] - A[0][1] * B[1];
  26. double detA2 = A[0][0] * B[1] - B[0] * A[1][0];
  27.  
  28. // Cramer's Rule solutions
  29. double x1 = detA1 / detA;
  30. double x2 = detA2 / detA;
  31.  
  32. System.out.println("\nSolution using Cramer's Rule:");
  33. System.out.println("x1 = " + x1);
  34. System.out.println("x2 = " + x2);
  35.  
  36. System.out.println("\nInverse of A:");
  37. double[][] inverse = {
  38. { A[1][1] / detA, -A[0][1] / detA },
  39. { -A[1][0] / detA, A[0][0] / detA }
  40. };
  41. printMatrix(inverse);
  42. }
  43.  
  44. public static void printMatrix(double[][] m) {
  45. for (double[] row : m) {
  46. for (double val : row)
  47. System.out.printf("%10.4f ", val);
  48. System.out.println();
  49. }
  50. }
  51. }
  52.  
Success #stdin #stdout 0.13s 56024KB
stdin
Standard input is empty
stdout
Matrix A:
    2.0000     5.0000 
   -3.0000     1.0000 

Vector B:
11.0
-4.0

Determinant of A: 17.0

Solution using Cramer's Rule:
x1 = 1.8235294117647058
x2 = 1.4705882352941178

Inverse of A:
    0.0588    -0.2941 
    0.1765     0.1176