-2

I wanted to write a program where the user can pass in the mathematical expression that they want to evaluate as a string.

So for instance, if the user enters a formula and other necessary arguments as string

sin(x**2)/x, 0, pi/2

and I want to process that as an integral with the help from math of sympy, how shall I do it? I know how the package sympy can process mathematical expressions, but I don't know how to do it when the expression is a string.

Thanks for the help!

pyjiang
  • 3
  • 1
  • 1
    If you can't find a package which does everything you need, then for a general solution you should research how to build a simple parser in Python. – Tim Biegeleisen Sep 22 '19 at 13:47
  • Possible duplicate of [python - From string to sympy expression](https://stackoverflow.com/q/33606667/4996248) – John Coleman Sep 22 '19 at 14:18

1 Answers1

1

You probably want the sympify function.

You can also use the split() function to split the string the user types into an array, in order to get the other necessary arguments you mention needing.

For example:

from sympy import sympify
def evaluate(x, args[]):
    # do stuff
    return answer
in = input("Enter your expression: ")
x = in.split(",")
print(evaluate(x[0], [x[1], x[2], ...]))

EDIT: Just realized I forgot to describe how to use sympify, which is probably the most important thing with this question. Here is a simple example that should get across how to use it:

x = sympify("x**2")
Nobozarb
  • 344
  • 1
  • 12
  • Thank you! Although I didn't eventually use this method, but the problem was solved nevertheless. – pyjiang Sep 23 '19 at 20:36
  • 1
    `sympy` uses `eval` under-the-hood, so it is not safe to use with user-supplied input. See https://github.com/sympy/sympy/issues/10805 – kaya3 Jan 13 '20 at 17:47