Sympy string to equation

Stack Overflow Asked by Mel on December 3, 2020

Im working on a project with sympy. I want to save some equations in a JSON file. They are saved as a string (for example: "R * C * 1.1, ti"). I have tried to convert the string to a equation (with sy.S() and sy.Eq()), but it didn’t work.

Here is my code:

import sympy as sy

def solve():

  R = sy.S(2)
  C = sy.S(1)
  ti = sy.S("ti")

  equation = sy.Eq(sy.S("R * C * 1.1, ti"))

  solution = sy.solve(equation, manual = 1)


I get this warning and a empty solution (when i exchange the string with a normal formula, it works):

Eq(expr) with rhs default to 0 has been deprecated since SymPy 1.5.
Use Eq(expr, 0) instead. See for more info.


One Answer

There are several issues:

  • sy.S("R * C * 1.1, ti") doesn't look at existing variables, but creates its own variables that happen to have the external names "R", "C" and "ti.
  • sy.S("R * C * 1.1, ti") creates a tuple (R * C * 1.1, ti)
  • sy.Eq() expects two parameters: the left-hand side and the right-hand side of an equation. Older versions of sympy where also happy with just the left-hand side and imagined the right-hand side to be 0. This still works, but is strongly discouraged as it won't work any more in future versions.
  • With sy.Eq(sy.S("R * C * 1.1, ti")), there is only one parameter (a tuple) for sy.Eq. So this provokes the deprecated warning.
  • To convert a tuple to parameters, Python now uses the * operator: func(*(a,b)) calls func with two parameters: func(a,b). On the other hand func((a,b)) calls func with just one parameter, the tuple (a,b).
  • To assign values to the variables obtained via sy.S("R * C * 1.1, ti"), a dictionary that maps strings to values can be used.
  • Although True and False are represented internally as 1 and 0, it is highly recommended to explicitly use the names. Among others, this helps with readability and maintainability of code.
import sympy as sy

def solve():
    value_dict = {"R": 2, "C": 1}
    equation = sy.Eq(*sy.S("R * C * 1.1, ti")).subs(value_dict)
    solution = sy.solve(equation, manual=True)


If you need ti to be an accessible sympy variable, you can add it to the dictionary:

    ti = sy.symbols("ti")
    value_dict = {"R": 2, "C": 1, "ti": ti}

Correct answer by JohanC on December 3, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP