Search code examples
pythonsympynonlinear-functions

SymPy: automatic construction of equations


I found elsewhere that x = sp.symbols('x1:{}'.format(n)) creates a collection of n variables, bound to a variable x. Now, I would like to use https://docs.sympy.org/latest/modules/solvers/solveset.html#sympy.solvers.solveset.nonlinsolve to solve a system of non-linear equations. I can construct a string containing the expression for each row in my system of equations, e.g. something like x1**2+4*x2**3 etc. How do I make sympy convert these into its own equations? In the examples given in the documentation, we write something like [x1**2+4*x2**3,2*x1+3*x3] and pass it to solve(), but how to construct these expressions (and what is their type?) automatically, short of hard-coding them?


Solution

  • The expressions above are sums of products of symbols, in sympy instances of Add

    From the documentation:

    All symbolic things are implemented using subclasses of the Basic class. First, you need to create symbols using Symbol("x") or numbers using Integer(5) or Float(34.3). Then you construct the expression using any class from SymPy. For example Add(Symbol("a"), Symbol("b")) gives an instance of the Add class. You can call all methods, which the particular class supports.

    In your example you need to declare x1, x2, x3 as symbols:

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

    Once the symbols are defined, sympy converts strings automatically to its own expressions for computing. To check the type of sympy expressions use sympify

    a = Symbol("a")
    b = Symbol("b")
    c = 'a**2 + b'
    print c
    (a + b)**2
    type(c)
    # string
    
    from sympy import sympify
    sympify(c)
    type(sympify(c))
    # <𝑐𝑙𝑎𝑠𝑠′𝑠𝑦𝑚𝑝𝑦.𝑐𝑜𝑟𝑒.𝑎𝑑𝑑.𝐴𝑑𝑑′>