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.
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 .
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.
Basics. Exact SymPy expressions can be converted to floating-point approximations (decimal numbers) using either the . evalf() method or the N() function.
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})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With