Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to answer the following problem

enter image description here

This I can do manually also, but let's say I am having 100 variables and 100 equations. So my problem is how to classify variables in order to solve this problem? How to collect all the variables in one vector and rewrite the system so I can solve it? In the end, all I want is number values for f1, x1, and x2.

1 Answer

0 votes
by (107k points)

I think you have to adjust the matrix of your problem to take care of RyA and other variables that on the right-hand side. You can also solve that manually or you can use sympy instead of np.linalg.solve() which can do the algebra section of the problem:

from sympy import Matrix, symbols, solve

x1, x2, f1 = symbols('x1 x2 f1')

X = Matrix([0, x1, x2])

B = Matrix([f1, 50, 60])

M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

solve(M * X - B, [x1, x2, f1])

# {f1: 40, x2: 100/3, x1: -30}

import numpy as np

from sympy import expand

def symbolic_to_matrix(F, variables):

    """

    F is a symbolic vector function that is a left-hand side of equation F = 0

    the variable is a list of variables (sympy.Symbol's) which F depends on.

    Assuming that there exists numeric matrix A such that equation F = 0

    is equivalent to linear equation Ax = b, this function returns 

    tuple (A, b)

    """

    A = []

    b = []

    for row in F:

        coeffs = expand(row).as_coefficients_dict()

        A.append([float(coeffs[x]) for x in variables])

        b.append(-float(coeffs[1]))

    return np.array(A), np.array(b)

A, b = symbolic_to_matrix(M * X - B, [x1, x2, f1])

# A

# array([[ 2.,  3., -1.],

#       [ 5.,  6.,  0.],

#       [ 8.,  9.,  0.]])

# b

# array([ -0.,  50.,  60.])

np.linalg.solve(A, b)

# array([-30.        ,  33.33333333,  40.        ])

Interested in learning Python? Enroll in our Python Course now! 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...