You need to find the values of x, y, and z that satisfy the system of linear equations shown in Figure 8-2.
Use the
RealMatrix
and RealMatrixImpl
from Commons Math. Represent
this system of linear equations as matrices in the
Ax=B
form, as shown in Figure 8-3. Place the coefficients of
A
in a RealMatrix
, and put
B
in a double[]
. Call the
solve( )
method on RealMatrix
to
retrieve a double[]
of values for x, y, and z that
satisfy this system of equations.
The following example takes the
coefficients
and constants from
Figure 8-3 and uses a RealMatrix
to solve this system:
import org.apache.commons.math.linear.RealMatrix; import org.apache.commons.math.linear.RealMatrixImpl; import org.apache.commons.lang.ArrayUtils; double[][] coefficients = { { 3.0, 20.0, 89.0 }, { 4.0, 40.0, 298.0 }, { 7.0, 21.0, 0.42 } }; double[] values = { 1324, 2999, 2039 }; RealMatrix matrix = new RealMatrixImpl( ); matrix.setData( coefficients ); double[] answers = matrix.solve( values ); System.out.println( "Answers: " + ArrayUtils.toString( answers ) );
This example solves this system of equations and prints out the
values of x, y, and z using Commons Lang
ArrayUtils
to print a double[]
:
Answers: {400.4839095455532,-36.59139305646149,9.599731825759218}
Using Commons Math, we find that the following values satisfy this system of equations: x = 400, y = -36, and z = 9.6.
To solve these equations, a double[][]
of
coefficients is created to represent a 3 3 matrix, and a
double[]
of constants is created. The
RealMatrix
interface is implemented by
RealMatrixImpl
, which stores a matrix as a
double[][]
; to populate this
double[][]
, pass the
double[][]
, coefficients
, to
the setData( )
method of
RealMatrixImpl
. To solve the system, the
values
double[]
is passed to
matrix.solve( )
, and a double[]
containing x, y, and z is returned.
This method will not work for every matrix; there are systems of
linear equations that are unsolvable. For example, if one attempts to
find values for the system of equations from Figure 8-4, an InvalidMatrixException
will be thrown stating that the matrix is singular. Additionally, if
the number of rows in B
does not equal the
number of columns in A
, solve()
will throw an InvalidMatrixException
.
For more information about solving systems of linear equations (or,
for that matter, information about anything), see Wikipedia
(http://en.wikipedia.org/wiki/System_of_linear_equations).
RealMatixImpl
uses a process known as LU
decomposition to solve this system of equations. For more information
about LU decomposition, see the JavaDoc for the
org.apache.commons.math.linear
package
(http://jakarta.apache.org/commons/math/apidocs/index.html).
18.191.181.252