Issue
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.
Solution
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('}', ')')
Answered By - Andrew-Harelson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.