Lukasz - 1 year ago 43

Python Question

Is there a way to solve a linear system of equations in python where the unknown is on both sides of the equality. So for instance if I have:

`x_1 = 0.7 + 0.5 * x_1 - 0.4 * x_2`

x_2 = 0.7 * x_1 + 0.5 - 0.4 * x_1

x_3 = 0.7 * x_2 + 0.5 * x_1 - 0.4

where this can be expressed as:

`|x_1| | 1 x_1 x_2|| 0.7|`

|x_2| = |x_1 1 x_1|| 0.5|

|x_3| |x_2 x_1 1 ||-0.4|

where the we have a Toeplitz Matrix.

I could easily solve such an expression by hand, but it gets laborious as I have large sets. I was looking at

Is there a python module to solve linear equations?

How to solve a pair of nonlinear equations using Python?

and the SymPy Solvers modules, but I can't seem to find a way of going about this.

Answer Source

You need to get your equations to form (x_3 omitted for obvious reasons)

```
0.5 * x1 + 0.4 * x2 = 0.7
0.7 * x1 - 1.4 * x2 = -0.5
```

before you can use `numpy.linalg.solve`

, like in this case

```
import numpy as np
a = np.array([[0.5, 0.4], # first row x_i factors
[0.7, -1.4]]) # second row x_i factors
b = np.array([0.7, -0.5])
sol = np.linalg.solve(a, b)
print sol
```

which gives

```
[ 0.79591837 0.75510204]
```

If the question is about how to transform the input

```
x_1 = 0.7 + 0.5 * x_1 - 0.4 * x_2
x_2 = 0.7 * x_1 + 0.5 - 0.4 * x_2
```

automatically to the form where constants are on the right side of the equations, it can be archieved by noting first that

```
0 + 1 * x_1 + 0 * x_2 = 0.7 + 0.5 * x_1 - 0.4 * x_2
0 + 0 * x_1 + 1 * x_2 = 0.5 + 0.7 * x_1 - 0.4 * x_2
```

and then placing those values in matrixes

```
import numpy as np
left = np.matrix([[0, 1, 0], # [cons., x_1, x_2]
[0, 0, 1]])
right = np.matrix([[0.7, 0.5, -0.4],
[0.5, 0.7, -0.4]])
tmp = left - right
constants = - tmp[:, 0]
factors = tmp[:, [1, 2]]
sol = np.linalg.solve(factors, constants)
print factors
print constants
print sol
```