Solve Equations in Python
Main.PythonSolveEquations History
Hide minor edits - Show changes to markup
The APMonitor Modeling Language with a Python interface is optimization software for mixed-integer and differential algebraic equations. It is coupled with large-scale solvers for linear, quadratic, nonlinear, and mixed integer programming (LP, QP, NLP, MILP, MINLP). Modes of operation include data reconciliation, real-time optimization, dynamic simulation, and nonlinear predictive control. It is freely available through MATLAB, Python, Julia, or from a web browser interface.
The Gekko Optimization Suite with a Python interface is optimization software for mixed-integer and differential algebraic equations. It is coupled with large-scale solvers for linear, quadratic, nonlinear, and mixed integer programming (LP, QP, NLP, MILP, MINLP). Modes of operation include data reconciliation, real-time optimization, dynamic simulation, and nonlinear predictive control.
where T is the temperature, V is the molar volume, `R_g` is the universal gas constant, and a and b are compound-specific constants. The solution for the molar volume of ethane for each phase at T = 77°C and P = 1 bar is shown below with Scipy fsolve and Gekko. For ethane, a = 2.877e8 cm^6 K^0.5 bar / mol^2 and b = 60.211 cm^3 / mol. The ideal gas law is a guess of the vapor volume and 1.1*b'' is a guess of the liquid volume.
where T is the temperature, V is the molar volume, `R_g` is the universal gas constant, and a and b are compound-specific constants. The solution for the molar volume of ethane for each phase at T = 77°C and P = 1 bar is shown below with Scipy fsolve and Gekko. For ethane, a = 2.877e8 cm^6 K^0.5 bar / mol^2 and b = 60.211 cm^3 / mol. The ideal gas law is a guess of the vapor volume and 1.1*b is a guess of the liquid volume.
where T is the temperature, V is the molar volume, `R_g` is the universal gas constant, and a and b are compound-specific constants. The solution for the molar volume of ethane for each phase at T = 77°C and P = 1 bar is shown below with Scipy fsolve and Gekko. For ethane, a = 2.877e8 `\frac{cm^6 K^{0.5} bar}{mol^2}` and b = 60.211 `\frac{cm^3}{mol}`. The ideal gas law is a guess of the vapor volume and 1.1*b is a guess of the liquid volume.
where T is the temperature, V is the molar volume, `R_g` is the universal gas constant, and a and b are compound-specific constants. The solution for the molar volume of ethane for each phase at T = 77°C and P = 1 bar is shown below with Scipy fsolve and Gekko. For ethane, a = 2.877e8 cm^6 K^0.5 bar / mol^2 and b = 60.211 cm^3 / mol. The ideal gas law is a guess of the vapor volume and 1.1*b'' is a guess of the liquid volume.
where T is the temperature, V is the molar volume, `R_g` is the universal gas constant, and a and b are compound-specific constants. The solution for the molar volume of ethane for each phase at T = 77°C and P = 1 bar is shown below with Scipy fsolve and Gekko. For ethane, a = 2.877e8 `\frac{cm^6-bar-K^{0.5}}{mol^2}` and b = 60.211 `\frac{cm^3}{mol}`. The ideal gas law is a guess of the vapor volume and 1.1*b is a guess of the liquid volume.
where T is the temperature, V is the molar volume, `R_g` is the universal gas constant, and a and b are compound-specific constants. The solution for the molar volume of ethane for each phase at T = 77°C and P = 1 bar is shown below with Scipy fsolve and Gekko. For ethane, a = 2.877e8 `\frac{cm^6 K^{0.5} bar}{mol^2}` and b = 60.211 `\frac{cm^3}{mol}`. The ideal gas law is a guess of the vapor volume and 1.1*b is a guess of the liquid volume.
where T is the temperature, V is the molar volume, `R_g` is the universal gas constant, and a and b are compound-specific constants. The solution for the molar volume of ethane for each phase at T = 77°C and P = 1 bar is shown below with Scipy fsolve and Gekko. For ethane, a = 2.877×10^8 `\frac{cm^6 bar K^{0.5}}{mol^2}` and b = 60.211 `\frac{cm^3}{mol}`. The ideal gas law is used to obtain the guess of the vapor volume and 1.1*b is used to obtain the guess for the liquid volume.
where T is the temperature, V is the molar volume, `R_g` is the universal gas constant, and a and b are compound-specific constants. The solution for the molar volume of ethane for each phase at T = 77°C and P = 1 bar is shown below with Scipy fsolve and Gekko. For ethane, a = 2.877e8 `\frac{cm^6-bar-K^{0.5}}{mol^2}` and b = 60.211 `\frac{cm^3}{mol}`. The ideal gas law is a guess of the vapor volume and 1.1*b is a guess of the liquid volume.
Equations with Multiple Solutions (Roots)
Nonlinear equations may have multiple solutions. An example from engineering is the Redlich/Kwong Equation of State (EOS) that has 3 roots (solutions) that are the liquid volume, the vapor volume, and an extra root that isn't physically meaningful.
$$P = \frac{R_g \, T}{V-b} - \frac{a}{T^{1/2} \, V \, \left(V+b\right)}$$
where T is the temperature, V is the molar volume, `R_g` is the universal gas constant, and a and b are compound-specific constants. The solution for the molar volume of ethane for each phase at T = 77°C and P = 1 bar is shown below with Scipy fsolve and Gekko. For ethane, a = 2.877×10^8 `\frac{cm^6 bar K^{0.5}}{mol^2}` and b = 60.211 `\frac{cm^3}{mol}`. The ideal gas law is used to obtain the guess of the vapor volume and 1.1*b is used to obtain the guess for the liquid volume.
(:source lang=python:) import numpy as np from scipy.optimize import fsolve
- constants
TC = 77 # degC P = 1.0 # bar a = 2.877e8 # cm^6 bar K^0.5 / mol^2 b = 60.211 # cm^3 / mol Rg = 83.144598 # cm^3 bar / K-mol
- derived quantities
TK = TC+273.15 # K Vg = Rg*TK/P # ideal gas guess
- Scipy fsolve solution
def f(V):
return P-Rg*TK/(V-b) + a/(np.sqrt(TK)*V*(V+b))
V = fsolve(f,Vg) print(f'Scipy Vapor Solution: {V[0]:0.1f} cm^3/mol') V = fsolve(f,b*1.1) print(f'Scipy Liquid Solution: {V[0]:0.1f} cm^3/mol')
- Gekko solutions
from gekko import GEKKO m = GEKKO(remote=False) V = m.Var(value=Vg,lb=1e4) m.Equation(P == Rg*TK/(V-b) - a/(np.sqrt(TK)*V*(V+b))) m.options.SOLVER=1; m.solve(disp=False) print(f'Gekko Vapor Solution: {V.value[0]:0.1f} cm^3/mol')
- update bounds and initial guess
V.lower=b*0.5; V.upper = b*2; V.value=b*1.1 m.options.SOLVER=1; m.solve(disp=False) print(f'Gekko Liquid Solution: {V.value[0]:0.1f} cm^3/mol') (:sourceend:)
(:html:)
<div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'apmonitor'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'https://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
(:htmlend:)
(:source lang=python:)
(:source lang=python -inline:)
Source Code for Nonlinear Solution
Source Code for Nonlinear Solution (fsolve)
from numpy import * from scipy.optimize import *
import numpy as np from scipy.optimize import fsolve
F = empty((3)) F[0] = pow(x,2)+pow(y,2)-20 F[1] = y - pow(x,2)
F = np.empty((3)) F[0] = x**2+y**2-20 F[1] = y - x**2
zGuess = array([1,1,1])
zGuess = np.array([1,1,1])
Symbolic Solutions
Source Code for Nonlinear Solution (gekko)
(:source lang=python:) from gekko import GEKKO m = GEKKO() x,y,w = [m.Var(1) for i in range(3)] m.Equations([x**2+y**2==20, y-x**2==0, w+5-x*y==0]) m.solve(disp=False) print(x.value,y.value,w.value) (:sourceend:)
Symbolic Solution with Sympy
h = sym.Eq(-2*x+y,-z)sourceend:)
h = sym.Eq(-2*x+y,-z)
$$z=c_1 - \frac{5}{2} +\frac{5 \sqrt{3}}{2}$$
$$z=-c_1 - \frac{5}{2} +\frac{5 \sqrt{3}}{2}$$
$$z=c_1 - \frac{5}{2} -\frac{5 \sqrt{3}}{2}$$
$$z=-c_1 - \frac{5}{2} -\frac{5 \sqrt{3}}{2}$$
The same approach applies to linear or nonlinear equations.
$$-\frac{1}{2}+\frac{\sqrt{3}}{2}$$
$$x=-\frac{1}{2}+\frac{\sqrt{3}}{2}$$ $$y=c_1 - \frac{3 \sqrt{3}}{2} +\frac{3}{2}$$ $$z=c_1 - \frac{5}{2} +\frac{5 \sqrt{3}}{2}$$
and a second solution:
$$x=-\frac{1}{2}-\frac{\sqrt{3}}{2}$$ $$y=c_1 + \frac{3 \sqrt{3}}{2} +\frac{3}{2}$$ $$z=c_1 - \frac{5}{2} -\frac{5 \sqrt{3}}{2}$$
$$-\frac{1}{2}+\frac{\sqrt(3)}{2}$$
$$-\frac{1}{2}+\frac{\sqrt{3}}{2}$$
Symbolic Solutions
Sympy is a package for symbolic solutions in Python that can be used to solve systems of equations.
$$2x^2+y+z=1$$ $$x+2y+z=c_1$$ $$-2*x+y=-z$$
(:source lang=python:) import sympy as sym sym.init_printing() x,y,z = sym.symbols('x,y,z') c1 = sym.Symbol('c1') f = sym.Eq(2*x**2+y+z,1) g = sym.Eq(x+2*y+z,c1) h = sym.Eq(-2*x+y,-z)sourceend:)
sym.solve([f,g,h],(x,y,z)) (:sourceend:)
When solved in an IPython environment such as a Jupyter notebook, the result is displayed as:
$$-\frac{1}{2}+\frac{\sqrt(3)}{2}$$
The APMonitor Modeling Language is optimization software for mixed-integer and differential algebraic equations. It is coupled with large-scale solvers for linear, quadratic, nonlinear, and mixed integer programming (LP, QP, NLP, MILP, MINLP). Modes of operation include data reconciliation, real-time optimization, dynamic simulation, and nonlinear predictive control. It is freely available through MATLAB, Python, Julia, or from a web browser interface.
The APMonitor Modeling Language with a Python interface is optimization software for mixed-integer and differential algebraic equations. It is coupled with large-scale solvers for linear, quadratic, nonlinear, and mixed integer programming (LP, QP, NLP, MILP, MINLP). Modes of operation include data reconciliation, real-time optimization, dynamic simulation, and nonlinear predictive control. It is freely available through MATLAB, Python, Julia, or from a web browser interface.
The APMonitor Modeling Language is optimization software for mixed-integer and differential algebraic equations. It is coupled with large-scale solvers for linear, quadratic, nonlinear, and mixed integer programming (LP, QP, NLP, MILP, MINLP). Modes of operation include data reconciliation, real-time optimization, dynamic simulation, and nonlinear predictive control. It is freely available through MATLAB, Python, Julia, or from a web browser interface.
import numpy as np A = np.array([ [3,-9], [2,4] ]) b = np.array([-42,2]) z = np.linalg.solve(A,b) print(z) M = np.array([ [1,-2,-1], [2,2,-1], [-1,-1,2] ]) c = np.array([6,1,1]) y = np.linalg.solve(M,c) print(y)
(:source lang=python:) import numpy as np
A = np.array([ [3,-9], [2,4] ]) b = np.array([-42,2]) z = np.linalg.solve(A,b) print(z)
M = np.array([ [1,-2,-1], [2,2,-1], [-1,-1,2] ]) c = np.array([6,1,1]) y = np.linalg.solve(M,c) print(y) (:sourceend:)
from numpy import * from scipy.optimize import * def myFunction(z): x = z[0] y = z[1] w = z[2]
(:source lang=python:) from numpy import * from scipy.optimize import *
def myFunction(z):
x = z[0] y = z[1] w = z[2]
F = empty((3)) F[0] = pow(x,2)+pow(y,2)-20 F[1] = y - pow(x,2) F[2] = w + 5 - x*y return F zGuess = array([1,1,1]) z = fsolve(myFunction,zGuess) print(z)
F = empty((3)) F[0] = pow(x,2)+pow(y,2)-20 F[1] = y - pow(x,2) F[2] = w + 5 - x*y return F
zGuess = array([1,1,1]) z = fsolve(myFunction,zGuess) print(z) (:sourceend:)
Linear and nonlinear equations can also be solved with Excel and Python. Click on the appropriate link for additional information and source code.
A = np.array(3,-9],[2,4?)
A = np.array([ [3,-9], [2,4] ])
M = np.array(1,-2,-1],[2,2,-1],[-1,-1,2?)
M = np.array([ [1,-2,-1], [2,2,-1], [-1,-1,2] ])
Source Code for Linear Solutions
import numpy as np A = np.array(3,-9],[2,4?) b = np.array([-42,2]) z = np.linalg.solve(A,b) print(z) M = np.array(1,-2,-1],[2,2,-1],[-1,-1,2?) c = np.array([6,1,1]) y = np.linalg.solve(M,c) print(y)
Source Code
Source Code for Nonlinear Solution
(:title Solve Equations in Python:) (:keywords Python, solve equations, linear, nonlinear:) (:description Python tutorial on solving linear and nonlinear equations with matrix operations (linear) or fsolve NumPy(nonlinear):)
The following tutorials are an introduction to solving linear and nonlinear equations with Python. The solution to linear equations is through matrix operations while sets of nonlinear equations require a solver to numerically find a solution.
Solve Linear Equations with Python
(:html:) <iframe width="560" height="315" src="https://www.youtube.com/embed/44pAWI7v5Zk" frameborder="0" allowfullscreen></iframe> (:htmlend:)
Solve Nonlinear Equations with Python
(:html:) <iframe width="560" height="315" src="https://www.youtube.com/embed/S4Qg2CsiIj8" frameborder="0" allowfullscreen></iframe> (:htmlend:)
Source Code
from numpy import * from scipy.optimize import * def myFunction(z): x = z[0] y = z[1] w = z[2] F = empty((3)) F[0] = pow(x,2)+pow(y,2)-20 F[1] = y - pow(x,2) F[2] = w + 5 - x*y return F zGuess = array([1,1,1]) z = fsolve(myFunction,zGuess) print(z)
Additional Tutorials
Linear and nonlinear equations can also be solved with Excel and Python. Click on the appropriate link for additional information and source code.
(:html:)
<div id="disqus_thread"></div> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'apmonitor'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'https://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="https://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
(:htmlend:)