问题
I was just wondering if there is a method to input a symbolic function in a python code?
like in my code I have:
from sympy import *
import numpy as np
import math
myfunction = input("enter your function \n")
l = Symbol('l')
print myfunction(l**2).diff(l)
If I put cos, sin or exp, as an input then I have an output of: -2*l*sin(l**2)
What If I want to make the input function more general, say a polynomial or a complex function, or maybe a function of combined cos, sin and exp ???
回答1:
If you need good support for symbolic funcions, you should consider using sage.
It is a preprocessor for python, with lots of math support including symbolic functions. Sage code can be intermixed with normal python-code.
The package is quite big, but I have good experiences with it. It is free and open-source.
回答2:
As a syntax, sin + cos simply isn't going to work very well. The simplest way to get the general case to work is to give sympy an expression to evaluate. We can let sympify do the hard work of turning a string into a sympy object:
>>> s = raw_input("enter a formula: ")
enter a formula: sin(x) + x**3
>>> s
'sin(x) + x**3'
>>> f = sympy.sympify(s)
>>> f
x**3 + sin(x)
After which we can substitute and evaluate:
>>> f.subs({'x': 2})
sin(2) + 8
>>> f.subs({'x': 2}).evalf()
8.90929742682568
See also my answer here for some other tricks you can pull with a bit of work:
>>> f = definition_to_function("f(x) = sin(x) + x**3")
>>> f(3)
27.14112000805987
来源:https://stackoverflow.com/questions/15369106/input-a-symbolic-function-in-a-python-code