Home > other >  Solve linear equation with 2 unkown and 3 equations in numpy with np.linalg.solve
Solve linear equation with 2 unkown and 3 equations in numpy with np.linalg.solve

Time:01-26

3 euqations with two unknow have 3 solutions: One solution, infinte solutions, no solution. How would you write this in Numpy to get the solutions? I tried it the way you would do it with 3 unknowns:

import numpy as np

a = np.array([-9,-8, 14])

A = np.array([[ 1, 2, -2],
              [-3,-1, 4],
              ])
x = np.linalg.solve(A, a)
print(x)

But gives an Error, as A is not square. Sadly if I remove the last column of a and A, although i get an answer the system might still have no solution as it might not fit in the third equation.

CodePudding user response:

You do all this using the lstsq method. For example,

a = np.array([-9,-8, 14])
A = np.array([[ 1, 2, -2],
              [-3,-1, 4],
              ])
x,err,rk = np.linalg.lstsq(A.T, a)[:3]
print(x)
print(err)
print(rk)

yields the output

[-3.  2.]
[9.98402083e-31]
2

From the fact that the error is zero (up to numerical precision), you know that this solution is exact, which is to say that A.T@x should exactly equal a. So, the system has at least one solution.

From the fact that the rank is 2 (which matches the number of columns in A.T), we deduce that A.T has a trivial nullspace, which means that any solutions are unique.

  •  Tags:  
  • Related