Nikola Stoilov
Nikola Stoilov

Reputation: 95

Resolving linear equations with parameters

Good evening,I'm a novice with python as well but I'd like to improve my skills by resolving daily problems. Today's task is to create a python program that can calculate a linear application such as :

50x1    - 15x2  - 25x3  + 48x4  =   22         
- 13x1  - 4x2   + 9x3   - 4x4   =   -25        
- 14x1  + 38x2  - 26x3  - 32x4  =   -8*u-38         
29x1    - 13x2  - 4x3   + 26x4  =   41

Typically I would resolve that by:

import numpy as np
a = np.array([[50,-15,-25,48],[-13,-4,9,-4],[-14,38,26,-32],[29,-13,-4,26]])
b = np.array([22,-25,-8*u-38,41])

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

That'd throw an error due to the letter "u" in the array B, how can I make it work ? Thanks for any suggestions.

Upvotes: 0

Views: 1293

Answers (2)

Tarifazo
Tarifazo

Reputation: 4343

you can set your equation as a function of u, in the simplest case:

a = np.array([[50,-15,-25,48],[-13,-4,9,-4],[-14,38,26,-32],[29,-13,-4,26]])

def solve(u):
    b = np.array([22,-25,-8*u-38,41])
    return np.linalg.solve(a,b)

The fact that your u is not in the matrix means that the system does not have one, many or none solutions for different u values. You can see that using the determinant (np.linalg.det(a)).

Upvotes: 0

tel
tel

Reputation: 13999

You can't solve for 4 unknowns with only 3 equations. My only possible advice would be to drop the u.

Edit

In general, linear system solvers like np.linalg.solve typically conform to the same rigid convention: the first input value should be a matrix of the coefficients of your xs, and the second input value should be a vector of constant values that represent the left-hand side of the individual equations. If your system isn't like this you'll have to first refactor it by hand so that it meets the standard convention. Otherwise, you'll have to look into using a more flexible solving system, such as solveset in Sympy.

Here's how to solve your system of equations in terms of u using Sympy:

import sympy as sym

x_0,x_1,x_2,x_3 = sym.symbols('x_:4')
u = sym.symbols('u')

lhs = [
    50*x_0 - 15*x_1 - 25*x_2 + 48*x_3,
    -13*x_0 - 4*x_1 + 9*x_2 - 4*x_3,
    -14*x_0 + 38*x_1 + 26*x_2 - 32*x_3,
    29*x_0 - 13*x_1 - 4*x_2 + 26*x_3
]
rhs = [22,-25,-8*u-38,41]

eqs = [l - r for l,r in zip(lhs, rhs)]
sym.nonlinsolve(eqs, [*xs])

Output:

{((1572*u + 176197)/34925, -4*(2341*u + 37266)/34925, -204*(u + 1)/1397, -2*(722*u + 21677)/6985)}

Upvotes: 1

Related Questions