How to calculate expression using sympy in python

Zeck picture Zeck · Aug 10, 2011 · Viewed 19.2k times · Source

I need a calculate below expression using sympy in python?

exp = '(a+b)*40-(c-a)/0.5'

In a=6, b=5, c=2 this case how to calculate expression using sympy in python? Please help me.

Answer

xubuntix picture xubuntix · Aug 10, 2011

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

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

from sympy import Symbol
a = 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})