How to calculate expression using sympy in python How to calculate expression using sympy in python python python

How to calculate expression using sympy in python


The documentation is here: http://docs.sympy.org/. You should really read it!

To "calculate" your expression, write something like this:

from sympy import Symbola = Symbol("a")b = Symbol("b")c = Symbol("c")exp = (a+b)*40-(c-a)/0.5

And that's it. If you meant something else by "calculate", you could also solve exp = 0:

sympy.solve(exp)> {a: [0.0476190476190476*c - 0.952380952380952*b],>  b: [0.05*c - 1.05*a],>  c: [20.0*b + 21.0*a]}

For everything else, you should really read the docs. Maybe start here: http://docs.sympy.org/0.7.1/tutorial.html#tutorial

UPDATE: since you added the values for a, b, c to the question, you can add this to the solution:

exp.evalf(subs={a:6, b:5, c:2})


You can convert your string into a sympy expression using the parse_expr() function in the module sympy.parsing.sympy_parser.

>>> from sympy.abc import a, b, c>>> from sympy.parsing.sympy_parser import parse_expr>>> sympy_exp = parse_expr('(a+b)*40-(c-a)/0.5')>>> sympy_exp.evalf(subs={a:6, b:5, c:2})448.000000000000


I realise this was already answered above, but in the case of getting a string expression with unknown symbols and needing access to those symbols, here is the code I used

# sympy.S is a shortcut to sympifyfrom sympy import S, Symbol# load the string as an expressionexpression = S('avar**2 + 3 * (anothervar / athirdvar)')# get the symbols from the expression and convert to a list# all_symbols = ['avar', 'anothervar', 'athirdvar']all_symbols = [str(x) for x in expression.atoms(Symbol)]# do something with the symbols to get them into a dictionary of values# then we can find the result. e.g.# symbol_vals = {'avar': 1, 'anothervar': 2, 'athirdvar': 99}result = expression.subs(symbols_vals)