[Python] How to solve a 3D system of equations in Python

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    I have a system of equations like this:

    [​IMG]

    The problem is that every component aij, xij and bi are vectors, or lists (change over years).

    So we have a nxnxd numpy matrix with the vector A (nxnxd), B (nxd) and X (nxnxd) and we need to solve that system. Is that possible in a vectorized way with numpy?

    We know that the system always have a solution This is a reduced example:

    import pandas as pd
    import sympy as sp

    # This code snippet demonstrates how to create a DataFrame with symbolic equations
    # Constant nodes are vectors (every entrance is the value per year)
    cte_nodes = {"a_11": [1, 2, 3], "a_12": [4, 5, 6], "a_13": [7, 8, 9],
    "a_21": [10, 11, 12], "a_22": [13, 14, 15], "a_23": [16, 17, 18],
    "a_31": [19, 20, 21], "a_32": [22, 23, 24], "a_33": [25, 26, 27]}
    # Every row is a system of equations, and every column is a variable x1, x2, x3
    # The equations are represented as a DataFrame
    eqs_df = pd.DataFrame([[sp.sympify("x1/a11 + a12"), sp.sympify("x1/a11 + a12"), sp.sympify("x1/a11 + a12")],
    [sp.sympify("x2/a21 + a22"), sp.sympify("x2/a21 + a22"), sp.sympify("x1/a11 + a12")],
    [sp.sympify("x3/a31 + a32"), sp.sympify("x3/a31 + a32"), sp.sympify("x1/a11 + a12")]]).T
    eqs_df.columns = ["x1", "x2", "x3"]

    # The system always have solution


    Again, the code below is just a simplification, but speed matters, because the original matrices are much larger. Thanks in advance.

    Continue reading...

Compartilhe esta Página