Friday, September 18, 2020

Solve Linear Equations in Three Variables - Using Python, Numpy and Sympy , With the Given Code

 Hi,

In the series of posts about Python for Civil Engineers, I have come with something from linear algebra.

While dealing with statics problems, such as finding unknown forces in space truss members, one has to deal with the system of linear equations in three variables. 


One can use the 'Sympy' and 'Numpy' libraries in Python can get a beautiful solution code for solving a system of linear equations in three variables. Computer programming is very much easy in Python, and you definitely need to try it. The code given below is separated into two parts: 1st part is the solution of the same problem using Sympy, and 2nd part gives solution code using Numpy library. 

The code is written specifically to solve the following three linear equations, but you can change the numbers accordingly.

x + 2y + 3z = 8

4x + 2y + 4z = 5

4x + 2y + 5z = 1

Simply change the coefficient for any other system. 


Code:

import numpy as np
import sympy as sp
from sympy import Eq, solve_linear_system, Matrix

# Using sympy

x,y,z = sp.symbols('x y z')
row1 = [1, 2, 3, 8]
row2 = [4, 2, 4, 5]
row3 = [4, 2, 5, 1]
system = Matrix((row1, row2, row3))
print(system)
print(solve_linear_system(system,x,y,z))

print('___________________________________ ')

# Using numpy
row1 = np.array([1,2,3])
row2 = np.array([4,2,4])
row3 = np.array([4,2,5])
constants = np.array([8,5,1])
system = np.array((row1, row2, row3))
print(system)
xyz= np.linalg.solve(system, constants)
print(xyz)


Thanks!

No comments:

Post a Comment

Resume-Now (BOLD LLC) is a FRAUD | defrauds Innocent Job Seekers

 Hi, Are you looking for a job change or a first-time job seeker?  I know, a somewhat difficult and desperate time it is sometimes.  In such...