[Math] Python Solving simultaneous equations with numpy

matricespythonsystems of equations

I wanted to solve a triplet of simultaneous equations with python. I managed to convert the equations into matrix form below:

Matrix array form of simultaneous equation

For example the first line of the equation would be

v0 = ps0,0 * rs0,0  + ps0,1 * rs0,1 + ps0,2 * rs0,2 
 + y(ps0,0 * v0     + ps0,1 * v1    + ps0,2 *v2)

I am solving for v0,v1,v2. I came across linalg.solve from the numpy library however I am really lost at rearranging the matrices in the form given in their examples because I have v0,v1,v2 in a [3×1] on the left and a [3×3] on the right.

Best Answer

I'll see if I can't help with the following...

I am really lost at rearranging the matrices in the form given in their examples


Here's some tips for going between matrices and Python lists and numpy arrays

$$ v = \begin{pmatrix} 9 \\\ 8 \\\ 7 \end{pmatrix} $$

Where I usually see $v_{\left(1\right)} = 9$ and $v_{\left(3\right)} = 7$ is written just a bit like...

vList = [9, 8, 7]
vArray = np.array(vList)

# vList[0]  # -> 9
# vArray[2] # -> 7

... and in most programming languages the index starts at 0, but it looks like you've got that.


Things get interesting with nested lists and multidimensional numpy arrays...

$$ p = \begin{pmatrix} 0.3 & 0.6 & 0.9 \\\ 0.4 & 0.7 & 0.8 \\\ 0.5 & 0.8 & 0.7 \end{pmatrix} $$

Which could be represented as a numpy.array as shown...

p = np.array([
    [0.3, 0.6, 0.9],
    [0.4, 0.7, 0.8],
    [0.5, 0.8, 0.7]
])

Accessing rows could then look like...

p[0]
# -> array([ 0.3,  0.6,  0.9])
p[2]
# -> array([0.5, 0.8, 0.7])

... but accessing cells is likely to frustrate those that want precision at a cellular level...

p[2,0]
# -> 0.5
# ... above looks okay...
p[0,0]
# -> 0.29999999999999999
# ... but that was `0.3`...
p[1,1]
# -> 0.69999999999999996
# ... and that should have been `0.7`

Even funkier than that...

p * 5
# -> array([[ 1.5,  3. ,  4.5],
#           [ 2. ,  3.5,  4. ],
#           [ 2.5,  4. ,  3.5]])

Hopefully this gave ya some traction on translating your problem into something that a computer will consider, as well as some pointers on how not to use numpy. It's fantastic but misusing it can lead to anger, and anger can lead to; well let's not even consider the paths divergent from light ;-)

Related Question