Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

How to solve a system of linear equations in Python with an iterative method?

$
0
0

I have a system of linear equations represented as strings in Python, and I need to find integer values (positive or negative) for each of the variables that satisfy all equations simultaneously without contradictions. The number of variables and equations can vary, so the solution should adapt accordingly.

Here's an example of such a system of equations:

from sympy import symbols, Eq, solveimport resystem_equations = ['5 = X0 + Y0', '6 = X0 + Y1', '5 = X0 + Y3', '5 = X0 + Y4', '3 = X1 + Y2', '0 = X2 + Y2', '1 = X2 + Y4']# Extract all variable names from the system of equationsvariable_names = list(set(re.findall(r'[XY]\d+', ''.join(system_equations))))# Create symbols for the variablesvariables = symbols(''.join(variable_names))

It is important to keep in mind that the program must adapt to the number of variables (Xi and Yj) or/and equations that there are, this is just an example, where we have 8 unknowns and 7 linear equations.

For this example, one of the possible solutions where there are integer values that satisfy all the equations simultaneously (without contradictions), could be:

# a (posible) correct outputvalues_of_int_decomposition_variables = [['X0', 2], ['X1', 1], ['X2', -2], ['Y0', 3], ['Y1', 4], ['Y2', 2], ['Y3', 3], ['Y4', 3]]

Note that if they manage to satisfy all the equations:

ij_number_to_decompose = Xi + Yj5 = 2 + 36 = 2 + 45 = 2 + 35 = 2 + 33 = 1 + 20 = 2 + (-2)1 = -2 + 3

In the case of equations with the value of 0 it must necessarily be decomposed into 2 values equal in magnitude but of opposite sign (X2 and Y2 should have opposite values)


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>