Reputation:
I am using quad method of Scipy library and I want to evaluate numerical integration of a function that entered by a user. The function is stored as a string. However, quad method does not except string input. So, how can I convert this string expression into a numerical value?
Assume that, the string expression is:
s1 = "5*x**2 - 4*x + 2" and lower_bound = 0 , upper_bound = 5
quad(s1, lower_bound, upper_bound)
I've tried splitting this string into tokens with respect to arithmetic symbols then invoke the quad method but the independent variable(x in this case) still remains as string.
How can I solve this problem?
Upvotes: 1
Views: 911
Reputation: 11591
You can use eval() like so:
>>> eval( "lambda x:x+1" )
<function <lambda> at 0x7f1b80d8ef28>
If you add a "lambda x:" string on the beginning of your expression, then use eval() on the result, eval will return a function which does what you want. You can then pass this function to your Scipy integrating function.
Note: eval will execute any code which is passed to it, therefore do not use it in a context where it would create a security problem. If this is an online application, then eval() is the wrong choice. If this is a desktop application, then the user can already do anything they want with the computer, and in this context eval() is fine.
Upvotes: 2
Reputation: 301
scipy.integrate.quad()
expects a function as its first argument (docs).
Here you can either use function or lambda expression:
lower_bound = 0
upper_bound = 5
def s1(x):
return 5*x**2 - 4*x + 2
quad(s1, lower_bound, upper_bound)
quad(lambda x: 5*x**2 - 4*x + 2, lower_bound, upper_bound)
If you wanted to parse from the symbolic expression in a string, as a quick hack you can use eval()
:
s1 = "5*x**2 - 4*x + 2"
quad(lambda x: eval(s1), lower_bound, upper_bound)
If you are doing a lot of symbolic maths, I would suggest you to use SymPy.
Upvotes: 0
Reputation: 1977
I'm not sure if there's too much you can do here except for:
eval
with lambda
could do the trick, it's rather not safe and will be slower. If you are expecting only polynomials you might want to take a look at NumPy Polynomial
module (link).Also, take a look at what's been already asked: Equation parsing in Python (SO).
Upvotes: 1