Solving a system of linear equations using matrices.
Here’s an example program in Java that solves a system of linear equations using matrices:
import java.util.Arrays; public class LinearEquationSolver { public static void main(String[] args) { double[][] coefficients = {{2, 1, -1}, {-3, -1, 2}, {-2, 1, 2}}; double[] constants = {8, -11, -3}; double[] solution = solveLinearEquation(coefficients, constants); System.out.println("Solution: " + Arrays.toString(solution)); } public static double[] solveLinearEquation(double[][] coefficients, double[] constants) { int n = coefficients.length; // Augmented matrix double[][] augmentedMatrix = new double[n][n + 1]; // Populate augmented matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { augmentedMatrix[i][j] = coefficients[i][j]; } augmentedMatrix[i][n] = constants[i]; } // Perform Gaussian elimination for (int i = 0; i < n - 1; i++) { if (augmentedMatrix[i][i] == 0) { // Swap rows to avoid division by zero for (int j = i + 1; j < n; j++) { if (augmentedMatrix[j][i] != 0) { swapRows(augmentedMatrix, i, j); break; } } } for (int j = i + 1; j < n; j++) { double ratio = augmentedMatrix[j][i] / augmentedMatrix[i][i]; for (int k = i; k <= n; k++) { augmentedMatrix[j][k] -= ratio * augmentedMatrix[i][k]; } } } // Back substitution double[] solution = new double[n]; for (int i = n - 1; i >= 0; i--) { double sum = 0; for (int j = i + 1; j < n; j++) { sum += augmentedMatrix[i][j] * solution[j]; } solution[i] = (augmentedMatrix[i][n] - sum) / augmentedMatrix[i][i]; } return solution; } public static void swapRows(double[][] matrix, int i, int j) { double[] temp = matrix[i]; matrix[i] = matrix[j]; matrix[j] = temp; } }
This program solves a system of linear equations represented by the `coefficients` matrix and `constants` array. The `solveLinearEquation` method uses Gaussian elimination and back substitution to solve the system. The solution is then returned as an array of doubles.
In the example given, the program solves the following system of linear equations:
2x + y – z = 8
-3x – y + 2z = -11
-2x + y + 2z = -3
The solution is printed to the console.
No comments yet! You be the first to comment.