Solving Linear Systems#
Teng-Jui Lin
Content adapted from UW CHEME 375, Chemical Engineering Computer Skills, in Spring 2021.
Python skills and numerical methods
Matrix inversion by
numpy.linalg.inv()
Solving linear systems by
numpy.linalg.solve()
ChemE applications
Balancing chemical equations
Balancing chemical equations#
Problem Statement. (FRB 4.62a) Mammalian cells convert glucose to glutamic acid by the reaction
Determine the stoichiometric coefficients.
Solution. We establish atomic balance between reactants and products:
Reorganize the equations so that variables are on the left and constant are on the right:
Because we have five variables but only four equations, we need to assume an arbitrary basis. Here, we can assume a basis of stoichiometric coefficient of \(\mathrm{C_5H_9NO_4}\) being one:
Now we have five variables and equations, so we can rewrite them to the form of
where
We can then solve for \(\mathbf{x}\) and get the coefficients:
The resulting coefficients are scalable, so we can scale them to whole number for reporting if needed.
Implementation: solving linear systems using numpy.linalg.inv()
#
In this approach, we use numpy.linalg.inv()
to solve the linear system by matrix inversion.
import numpy as np
from numpy.linalg import inv
# define the matrix and vector
A = np.array([[0, 0, 5, 1, 0],
[-3, 0, 9, 0, 2],
[0, -2, 4, 2, 1],
[1, 0, -1, 0, 0],
[0, 0, 1, 0, 0]])
b = np.array([6, 12, 6, 0, 1])
# calculate the unknown vector using inverse and matrix multiplication
x = inv(A) @ b
x
array([1. , 1.5, 1. , 1. , 3. ])
Therefore, we have the solution
We have the balanced chemical equation
Implementation: solving linear systems using numpy.linalg.solve()
#
In this approach, we use numpy.linalg.solve()
to directly solve the linear system.
from numpy.linalg import solve
x = solve(A, b)
x
array([1. , 1.5, 1. , 1. , 3. ])
This approach gives the same result and is computationally more efficient.