0

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.

Withi Weis
  • 53
  • 5

1 Answers1

3

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.

Ben Grossmann
  • 4,387
  • 1
  • 12
  • 16
  • https://riptutorial.com/numpy/example/16034/find-the-least-squares-solution-to-a-linear-system-with-np-linalg-lstsq – Withi Weis Jan 25 '22 at 21:15