Home:ALL Converter>Sympy solve linear system of equations

Sympy solve linear system of equations

Ask Time:2020-03-27T11:41:43         Author:rfs_

Json Formatter

I've create a linear system of equations in a for loop using sympy symbols and stored all equations in a numpy array. In the present moment I'm using sympy.linear_eq_to_matrix to "transform" the equations in to a matrix and solve then. But, this process using sympy.linear_eq_to_matrix is taking a long time when I've a lot of variables. So, to avoid sympy.linear_eq_to_matrix, what is the best alternative ? Can I solve the system without pass through sympy.linear_eq_to_matrix ? I'm just writing a simple script.

## I've imported all libs.
comp = 5
h = 0.1
nodes = int(((comp/h)+3))
a = np.array(sp.symbols("w0:"+str(nodes**2)))
w = np.reshape(a, (nodes,nodes))
equations = np.array([])

## In this interval I've some for loop to apply boundary conditions.

for i in range(2, (nodes-2)):
 for j in range(2, (nodes-2)):
  eq = Eq(5*(w[i,j]) + w[i,j-2]), 0.1) ## This equation is more complex, I reduced.
  equations = np.append(equations, eq)

hg = np.array([]) ## hg = just some variables to solve.
for i in range(2, (nodes-2)):
 for j in range(2, (nodes-2)):
  hg = np.append(hg, w[i,j])

system, equality =sp.linear_eq_to_matrix(equations, hg) ## THE PROBLEMATIC PART
system_array = np.array(system).astype(np.float64)
system_equality = np.array(equality).astype(np.float64)

ans = np.linalg.solve(system_array, system_equality)
print("\nAnswer")
print(ans)

Author:rfs_,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60879706/sympy-solve-linear-system-of-equations
yy