Solving Linear Systems#

Teng-Jui Lin

Content adapted from UW CHEME 375, Chemical Engineering Computer Skills, in Spring 2021.

Balancing chemical equations#

Problem Statement. (FRB 4.62a) Mammalian cells convert glucose to glutamic acid by the reaction

C6H12O6+aNH3+bO2pC5H9NO4+qCO2+rH2O

Determine the stoichiometric coefficients.

Solution. We establish atomic balance between reactants and products:

C balance:6=5p+qH balance:12+3a=9p+2rO balance:6+2b=4p+2q+rN balance:a=p

Reorganize the equations so that variables are on the left and constant are on the right:

C balance:5p+q=6H balance:9p+2r3a=12O balance:4p+2q+r2b=6N balance:ap=0

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 C5H9NO4 being one:

Basis:p=1

Now we have five variables and equations, so we can rewrite them to the form of

Ax=b

where

A=[0051030902024211010000100],b=[612601],x=[abpqr]

We can then solve for x and get the coefficients:

A1Ax=A1bx=A1b

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

x=[abpqr]=[11.5113].

We have the balanced chemical equation

C6H12O6+NH3+1.5O2C5H9NO4+CO2+3H2O

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.