Skip to content
Advertisement

How do I numerically integrate a string with variables in python?

Disclaimer: total noob here, please keep it as simple as possible

My plan was to use scipy.integrate.quad() and eval() (code inection won’t be a problem in my case). This works fine when the only variable in the equation is the integration variable:

from scipy.integrate import quad

equation = '1+2*x'

result = quad(lambda x: eval(equation), 0, 1)

Adding addtional variables works as long as they are defined:

from scipy.integrate import quad

equation = 'A+B*x'
A=1
B=2

result = quad(lambda x: eval(equation), 0, 1)

However if i try to give eval() those additional variables with a dictionary like I’m supposed to, it suddenly starts complaining that it can’t find x:

from scipy.integrate import quad

equation = 'A+B*x'
paramsDict = {'A':1, 'B':2}

result = quad(lambda x: eval(equation, paramsDict), 0, 1)

>>> NameError: name 'x' is not defined

So apparently eval() can return a function with an undefined variable no problem unless I give it some values to work with? How can I work around this?

Advertisement

Answer

If you take a look at the documentation for eval, you’ll see that the second parameter sets the scope of what the eval function can see, specifically it provides the set of globals that eval can utilize. Therefore, in your case it will lose access to x. This can be fixed in several ways, my quick and dirty solution is the following:

result = quad(lambda x: eval(equation, {**paramsDict, 'x':x}), 0, 1)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement