2

I'm writing an application in Python 3 that processes a lot of mathematical equations. In theory, I'd have to write a different function inside the code each time I need this application. I'd like to enter a function (a mathematical function) from keyboard, to save a lot of time and make this application more versatile.

For example:

def readfunction():
    func = input("Type the function you want to solve: ")
    return func
def solve(function)
    # does stuff

solve(readfunction)

The question is about "interpreting" input so that, say, if I type x+sin(x) each part is recognised as separate to like x is a variable which I can assign a value to (thus creating a new variable that is NOT in the original code), + is an operator and sin is a function from the module math. That way I can manipulate the function as I please.

How would I do that?

  • possible duplicate of [How do I execute a string containing Python code in Python?](http://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python) – Joe Oct 26 '11 at 15:53

2 Answers2

2

Take a look at Sage.

It's an awesome Python-based CAS that does exactly what you wish.

You can import Sage's modules and use its equation parser, as that can handle functions, variables, solve for variables, simplify, etc.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • I knew this program, but I missed the fact that I could import its modules. Thanks. –  Oct 26 '11 at 16:21
1

Use compile, eval and exec to create and execute code objects from a string at runtime. See documentation at http://docs.python.org/library/functions.html#compile. If you really want to process mathematical formulas, posting Equation parsing in Python may be of interest as well.

Community
  • 1
  • 1
hochl
  • 12,524
  • 10
  • 53
  • 87