Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate expression using sympy in python

Tags:

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.

like image 619
Zeck Avatar asked Aug 10 '11 06:08

Zeck


People also ask

How do you evaluate expressions in SymPy?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .

How do you use SymPy in Python?

SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible.

How do you approximate in SymPy?

Basics. Exact SymPy expressions can be converted to floating-point approximations (decimal numbers) using either the . evalf() method or the N() function.


2 Answers

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}) 
like image 57
xubuntix Avatar answered Sep 17 '22 19:09

xubuntix


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 
like image 43
jamesadney Avatar answered Sep 17 '22 19:09

jamesadney