8.7. Solving a System of Linear Equations
Problem
You need to find the values of x, y, and z that satisfy the system of linear equations shown in Figure 8-2.
Figure 8-2. A system of linear equations
Solution
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.
Figure 8-3. System of linear equations in Ax=B form
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
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.