So I am trying to convert a string function expression, to an a function which can take a numpy array ideally.
So far I have this:
import sympy as sp
expr = "x^2 y^2"
f = sp.sympify(expr)
symbol_list = []
for symbol in f.free_symbols:
symbol = sp.Symbol(str(symbol))
symbol_list.append(symbol)
Now the function f
will be able to be used using sp.subs
but I want to substitute a numpy array for x, y
.
Any ideas?
CodePudding user response:
Within SymPy, f
is called symbolic expression. Sympy also exposes lambdify
, which allows to convert a symbolic expression to a numerical function.
# extract the symbols from the symbolic expression: order them alphabetically.
# This will be used to create the signature of the numerical function.
signature = sorted(f.free_symbols, key=str)
print(signature)
# out: [x, y]
# create the numerical function
num_f = lambdify(signature, f)
# evaluation
import numpy as np
x = np.arange(1, 10)
y = 2
print(num_f(x, y))
# out: array([ 5, 8, 13, 20, 29, 40, 53, 68, 85])