Solving Equations¶
For problems that arise in first and second year Physics, it is usually advisable to solve the problem symbolically and then use the computer to compute the result based on your solution. Here we look at a couple exceptions to this rule.
from numpy import *
Systems of Linear Equations¶
When you have two or more equations in the form
$$ \begin{matrix} C_{11} x_1 + C_{12} x_2 + ... & = & S_1 \\ C_{21} x_1 + C_{22} x_2 + ... & = & S_2 \\ ... & & \end{matrix}$$
where the $C_{ij}$ are constant coefficients and the $S_i$ are also constants, solution by hand can be tedious and error-prone.
The computer can solve this by matrix methods. (You learn about this in linear algebra, but if you haven't yet studied that don't worry.) The trick is to write the coefficients as a matrix that is multiplied to a column of variables.
For example, the two equations
$$Ax + By = E\\ Cx + Dy = F $$
are written as
$$\begin{bmatrix}A & B \\ C & D \end{bmatrix} \begin{bmatrix} x\\ y\end{bmatrix} = \begin{bmatrix} E\\ F\end{bmatrix} $$
Now Python can solve this with its linear algebra routines as follows.
Two Linear Equations¶
Solve the following equations for $x$ and $y$:
$$ 5x+4y=-1 \\ -7x-2y=-13 $$
Get the problem into matrix form:
$$\begin{bmatrix}5 & 4 \\ -7 & -2 \end{bmatrix} \begin{bmatrix} x\\ y\end{bmatrix} = \begin{bmatrix} -1\\ -13\end{bmatrix} $$
And let numpy.linalg do the rest:
CC = array((( 5., 4. ),
( -7., -2. )))
SS = array(( -1., -13. ))
solution = linalg.solve(CC,SS)
print (solution)
[ 3. -4.]
That is, $x=3$ and $y=-4$ solve our system of equations.
Three Linear Equations¶
Solve the following equations for $x$, $y$ and $z$:
$$ 2x+-y+3z=37 \\ x+y-3z=-16 \\ -3x+5z=24 $$
Generalizing to three or more equations is straightforward.
CC = array((( 2, -1, 3 ),
( 1, 1, -3 ),
( -3, 0, 5 )))
SS = array(( 37,-16, 24 ))
solution = linalg.solve(CC,SS)
print (solution)
[7. 4. 9.]
Solution: $x=7$, $y=4$, $z=9$