Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python (SymPy, SciPy), create symbol lambda from string

I've struggling to take text inputs of an equation and evaluate it as a definite integral. I need a callable function to pass 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
like image 878
Nona Urbiz Avatar asked Sep 27 '26 03:09

Nona Urbiz


2 Answers

Not sure, but maybe you are looking for

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

Note that using eval() is dangerous if eq is from an untrusted source (e.g. user input).

like image 121
Sven Marnach Avatar answered Sep 28 '26 15:09

Sven Marnach


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
like image 43
rzetterberg Avatar answered Sep 28 '26 17:09

rzetterberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!