I want to take an equation from users to pass into my data to get the values. I was trying to use eval and using logic to find exp, log, and replace it with math function. However, eval is not supporting curly brackets or box brackets.
My equation will have only one independent variable (i.e y = f(x)). My current approach is following:
import math
x = 5
eqn = '(x**2) (x*2) exp(5) exp(2) log(2)'
if 'exp' in eqn:
eqn = eqn.replace('exp' , 'math.exp')
if 'log' in eqn:
eqn = eqn.replace('log' , 'math.log')
print(eval(eqn))
How do I support other brackets? Is there any better approach than this? Thanks.
CodePudding user response:
Python reserves [] and {} braces for other uses rather than just order of operations. You can just use nested parenthesis for the same effect.
More traditional mathematical notation would write nested parenthesis like this: [(2 2)*4]**2
In python, you could just write ((2 2)*4)**2
You could convert them like you've done with the other equation elements:
eqn = eqn.replace('[', '(')
eqn = eqn.replace('{', '(')
eqn = eqn.replace(']', ')')
eqn = eqn.replace('}', ')')
CodePudding user response:
SymPy's solve() function can be used to solve equations and expressions that contain symbolic math variables.
Equations with one solution: The code section below demonstrates SymPy's solve() function when an equation is defined with symbolic math variables.
from sympy import symbols, Eq, solve
y = symbols('y')
eq1 = Eq(y 3 8)
sol = solve(eq1)
sol
Output:
[-11]
Equations with two solutions:
If you specify the keyword argument dict=True to SymPy's solve() function, the output is still a list, but inside the list is a dictionary that shows which variable was solved for.
from sympy import symbols, Eq, solve
y = symbols('x')
eq1 = Eq(x*2 -5x 6)
sol = solve(eq1, dict=True)
sol
Output:
[{x: 2}, {x: 3}]