pythonpython-2.7sympyequationequation-solving

Solving a system of equation with Sympy, python2.7


I want to solve a system of equations. But I want to be able to precise the value to "get", and as a function of "what".

To better understand, I take an example from here, which I modified:

import sympy as sp
x, y, z = sp.symbols('x, y, z')
rho, sigma, beta = sp.symbols('rho, sigma, beta')
f1 = sigma * (y - x)
f2 = x * (rho - z) - y
f3 = x * y - beta * z
print sp.solvers.solve((f1, f2, f3), (x, y, z))

in

import sympy as sp
x, y, z, w = sp.symbols('x, y, z, w')
rho, sigma, beta = sp.symbols('rho, sigma, beta')
f1 = sigma * (y - x)
f2 = x * (rho - z) - y
f3 = x * y - beta * w
f4 = z - w
print sp.solvers.solve((f1, f2, f3, f4), (x, y, z))

So, as you can see, I replace z by w in the last equation and I add a new to precise z = w. But, sympy (on python 2.7) is unable to solve this new system of equation!!

So my question: How to get the result for x, y, z as a function of rho, sigma, beta. And more generally, how do we precise the variable "response variable".

I think that could be very helpful because, often, you don't want to develop your system of equation before asking python to solve it.

In the same way, if I take a more complex example:

import sympy as sp
x, y, z, w, u = sp.symbols('x, y, z, w, u')
rho, sigma, beta = sp.symbols('rho, sigma, beta')
f1 = sigma * (y - x)
f2 = x * (rho - u) - y
f3 = x * y - beta * w
f4 = z - w
f5 = w - u
print sp.solvers.solve((f1, f2, f3, f4, f5), (x, y, z))

The response I get is:

[]

But as you see I have z = w = u Son I should get the same answer!


Solution

  • Your code is giving following error:

    Traceback (most recent call last): File "C:\temp\equation1.py", line 37, in f3 = x * y - beta * w NameError: name 'w' is not defined

    Hence we pull symbol 'w' from sympy symbols as below x, y, z, w = sp.symbols('x, y, z, w')

    You also mentioned you are trying to add z = w , so once we add that to your code, it works.

    Working Code:

    import sympy as sp
    x, y, z, w = sp.symbols('x, y, z, w')
    rho, sigma, beta = sp.symbols('rho, sigma, beta')
    z = w
    f1 = sigma * (y - x)
    f2 = x * (rho - z) - y
    f3 = x * y - beta * w
    f4 = z - w
    print sp.solvers.solve((f1, f2, f3, f4), (x, y, z, w))
    

    Output:

    Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> ================================ RESTART ================================
    >>> 
    [(0, 0, 0), (-sqrt(beta*rho - beta), -sqrt(beta*(rho - 1)), rho - 1), (sqrt(beta*rho - beta), sqrt(beta*(rho - 1)), rho - 1)]
    >>>