1
$\begingroup$

I'm trying to find the intersection of lines $y=a_1x+b_1$ and $y=a_2x+b_2$ using numpy.linalg.solve(). What I can't get my head around is how to correctly make $A$ a square matrix for solve() to work. I'm familiar with solving linear equation systems, but there's something here I don't get.

What I'd like to do is:

def meeting_lines(a1, b1, a2, b2):
    a = np.array([[a1], [a2]])
    b = np.array([b1, b2])
    return np.linalg.solve(a, b)

def main():
    a1=1
    b1=4
    a2=3
    b2=2

    y, x = meeting_lines(a1, b1, a2, b2)

Where I expect $y=-3$ and $x=1$. However, this fails with numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square.

Thank you very much for your help, trying to figure this out has messed up my day already!

$\endgroup$
  • $\begingroup$ NB: I must use numpy.linalg.solve(). $\endgroup$ – basse Apr 1 at 12:49
1
$\begingroup$

You should formulate your lines as follows to have $(x, y)$ as unknowns: $$\begin{align} \left.\begin{matrix} a_1x-y=-b_1\\ a_2x-y=-b_2 \end{matrix}\right\} \rightarrow \overbrace{ \begin{bmatrix} a_1& -1\\ a_2& -1 \end{bmatrix} }^{\boldsymbol{a}} \overbrace{ \begin{bmatrix} x\\ y \end{bmatrix} }^{\boldsymbol{x}} = \overbrace{ \begin{bmatrix} -b_1\\ -b_2 \end{bmatrix} }^{\boldsymbol{b}} \end{align}$$ Therefore, the code should be:

import numpy as np

def meeting_lines(a1, b1, a2, b2):
    a = np.array([[a1, -1], [a2, -1]])
    b = np.array([-b1, -b2])
    return np.linalg.solve(a, b)

a1=1
b1=4
a2=3
b2=2
x, y = meeting_lines(a1, b1, a2, b2)
print(x, y)

which outputs:

1.0 5.0
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.