Python (SymPy, SciPy), create a lambda character from a string

I struggle to take the text inputs of the equation and evaluate it as a definite integral. I need the called function to go to scipy.integrate.

eq = "x**2"
func = lambda x: eq
func(2)

# outputs:
# x**2


# but if I:

func = lambda x: x**2
func(2)

# outputs:
# 4
+3
source share
5 answers

Not sure, but maybe you're looking

eq = "x**2"
func = eval("lambda x: " + eq)

Please note that use eval()is dangerous if it eqis from an untrusted source (e.g. user input).

+5
source

You need to use eval to run eq as code and not treat it as a string.

eq = "x**2"
func = lambda x: eval(eq)
func(2)

# outputs:
# 4
+2
source

sympify , . sympy.

:

import sympy as sp
f=sp.sympify('x**2+sin(y)')

autowrap sympy .

+2

Try asteval or numexpr for the more secure alternatives to eval () and Sympy.sympify (). evalf ().

+1
source

I kept getting a syntax error for the following and relentlessly tried to figure out why:

E="2x+1"
F=lambda x: (x, eval(E)) # to get an xy coordinate 

But the problem worked as expected when I changed E to:

E="2*x+1"

Newbie mistake. :)

0
source

All Articles