2

I am writing a python script that needs to take an equation from a user in the form of something like this

z=x^2+3x+9 +y^3 or z =cos(pi/2+x) + 2sin(y)

and evaluate the function at runtime over many values for x and y. How would I go about using the input given by a user as a function? Meaning I would like to be able to do something like this:

input = input("please input 3 variable function.")
function = evaluate_function(input)
for x and y:
        result = evaluate function
        return result

Is something like this possible? I have looked around and the closed thing I have found to what I want to do seems to be this (How to process user supplied formulas?), but it is only talking about evaluating for a single value of x and z not iterating over many values. Any help would be greatly appreciated.

Update: As suggested below I found this (http://lybniz2.sourceforge.net/safeeval.html) about using eval() which seems to be pretty much what I want to do

Community
  • 1
  • 1
guribe94
  • 1,551
  • 3
  • 15
  • 29

2 Answers2

0

Interpreting math formulas is sympy's domain. parse_expr is its safe parsing function, and its global_dict and local_dict arguments govern what predefined symbols are available.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
0

Yes, parsing and substitution should work:

from sympy.parsing.sympy_parser import parse_expr
eq = parse_expr(raw_input('enter an equation of x, y and/or z'))
for v in ((1,2,3),(1,2,4)):
  res = eq.subs(dict(zip((x,y,z),v)))
  dat = (tuple(v) + (eq, res))
  print('at x=%s, y=%s, z=%, %s = %s' % dat)
smichr
  • 16,948
  • 2
  • 27
  • 34