This module helps solve systems of linear equations. There are several ways of doing this. The first is to just pass the coefficients as a list of lists. Say we want to solve the system of equations: $$ \begin{array}{c|c|c} x - y = 5\\ x + y = -1 \end{array} $$ This is done with a simple call to linear_solver.solve_linear_system(), like so


In [6]:
import linear_solver as ls

xs = ls.solve_linear_system(
    [[1, -1, 5], 
     [1, 1, -1]])
print(xs)


[[ 2.]
 [-3.]]

Clearly, the solution set $(2, -3)$ satisfies the two equations above.

If a system of equations that has no unique solutions is given, a warning is printed and None is returned.


In [7]:
xs = ls.solve_linear_system(
    [[1, 1, 0],
    [2, 2, 0]])
print(xs)


Determinant of coefficients matrix is 0. No unique solution.
None

In [8]:
xs = ls.solve_linear_system(
    [[1, 1, 0],
    [2, 2, 1]])
print(xs)


Determinant of coefficients matrix is 0. No unique solution.
None

Additionally, the coefficients of the equation can be read from a text file, where expressions are evaluated before they are read. For example, consider the following system of equations:

$$ \begin{array}{c|c|c|c} 22m_1 + 22m_2 - m_3 = 0\\ (0.1)(22)m_1 + (0.9)(22)m_2 - 0.6m_3 = 0\\ \frac{22}{0.68} m_1 + \frac{22}{0.78} m_2 = (500)(3.785) \end{array} $$

We can put these coefficients into a text file, 'coefficients.txt', which has the contents

\# contents of coefficients.txt
22 22 -1 0
0.1\*22  0.9\*22 -0.6 0
22/0.68 22/0.78 0 500\*3.785
and then pass that file to the solver function.


In [9]:
sol = ls.solve_linear_system('coefficients.txt')
for i, row in enumerate(sol):
     print('m_{0} = {1:.2f}'.format(i, row[0,0]))


m_0 = 23.85
m_1 = 39.74
m_2 = 1399.00