Porada Kev
Porada Kev

Reputation: 513

Solving linear equations in Python (not working using linalg.solve)

Probably this is a very beginner question. I am new to python and such operation. But would appreciate any help. I am trying to solve a system of linear equations in Python, using numpy linalg.

x+y+z = 2

2x-6y-z=-1

3x-2z=8

I tried to use linalg.solve() function

a = np.array([[1,2,3],[1,-6,0],[1,-1,-2]])
b = np.array([2,-1,8])
try:
    x1 = linalg.solve(a,b)
except LinAlgError:
    x1 = linalg.lstsq(a,b)[0]
print(x1)
print(np.dot(a,x1) == b)

Here is the output

[ 5.38709677  1.06451613 -1.83870968]
[ True  True  True]

However, this doesn't work if we put these received values instead x,y,z in equations.

I tried another approach

x = np.dot(np.linalg.inv(a), b)
print(x)
print(np.dot(a,x) == b)

I received the same output as before:

 [ 5.38709677  1.06451613 -1.83870968]

This method only worked if we change the places of b and np.linalg.inv(a). Now it gives correct output.

x = np.dot(b, np.linalg.inv(a))
print(x)
print(np.dot(x,a) == b)

It works in equations

[ 2.  1. -1.]

So, here is the question. Could anyone please explain why cannot I get [ 2. 1. -1.] using linalg.solve?

Upvotes: 2

Views: 7237

Answers (2)

fuglede
fuglede

Reputation: 18201

The matrix a describing the left-hand side of the equation is set up the wrong way around;

 np.linalg.solve(a.T, b)

does what you want to do with the given a.

That your second approach does the job boils down to the fact that for any 2-dimensional ndarray a, and any 1-dimensional ndarray x for which the shapes match, np.dot(a, x) will equal np.dot(x, a.T). This is the case since in the two operations, viewed as matrix multiplications, x is treated as a column and row vector respectively, and for any matrix $A$ and any vector $x$, $Ax = (x^TA^T)^T$.

Upvotes: 4

Bailey Parker
Bailey Parker

Reputation: 15905

Looks like your a does not match the equations you wrote at the beginning of your question. You have

a = np.array([[1,2,3],[1,-6,0],[1,-1,-2]])

Which corresponds to:

  • x + 2y + 3z
  • x - 6y
  • x - y - 2z

Which isn't what you put at the top of your question.

Note that the [True, True, True] is showing you this. The fact that the dot product produced values matching b indicates that it did solve for the a and b in your code.

Upvotes: 3

Related Questions