Sometimes it is necessary to solve a system of linear equations in Java and you cannot write your own solver or you have not time for it and you do not care about performance. I assume that the reader is familiar with algebra and theory about the solving methods. Simplified, there are 3 types of linear equation:

  • underdetermined - the number of equations is less than the number of unknown
  • with square matrix - the number of equations is equal to the number of unknown
  • overdetermined - the number of equations is higher than the number of unknown

In the upcoming text, we are dealing with the second and third case. The system of the linear equation can be written as Ax=b. In the case of an overdetermined system, a solution in the sense of the least squares method can be obtained as (A’WA)x=A’Wb where W is the weight matrix (can be unit matrix). Considering that matrix A is written as systemMatrix and vector b is written as rightVector then the java code of the solution can be

// least square method
RealMatrix matrix = systemMatrix.transpose().multiply(weightMatrix).multiply(systemMatrix);
RealVector right = systemMatrix.transpose().multiply(weightMatrix).operate(rightVector);
// solver
ConjugateGradient cgm = new ConjugateGradient(10000, conjugateGradientPrecision, false);

RealVector init = ... // some initial solution
RealVector x = cgm.solve((AbstractRealMatrix) matrix, right, init);

This solution is based on the conjugate gradient method. You can also use some decomposition here. Using Singular Value Decomposition:

DecompositionSolver solver = new SingularValueDecomposition(systemMatrix).getSolver();
RealVector x = solver.solve(rightVector);