Define function from SymPy symbols

Viewed 220

I am using SymPy for analytical handling of variables (e.g. matrix multiplication etc.). After doing so, I end up with a new SymPy expression which I would like to use for plotting with Matplotlib. So far, my only way to do so, was to print the SymPy expression and paste it into a newly defined function manually.

How can I directly convert the SymPy expression into a function for numerical interpretation without relying on copying and pasting?

A minimal working example is the following:

import sympy as sp
import matplotlib.pyplot as plt
import numpy as np

sp.var('x A B') # x will later be the variable, A and B will be constants
temp = A*x+B # intermediate calculations
f = temp*x # function in reality, it will be more complicated.
print(f) # I printed f in order to find the expression and copy-pasting it into the function below.

def func(x,A,B):
    return x*(A*x + B) # This statement was copy-pasted. This line should be changed, s.t. copy-pasting is not necessary!

#Now we can handle the function numerically for plotting (using matplotlib and numpy)
xspace = np.linspace(0,5)
plt.plot(xspace,func(x=xspace,A=1,B=2))
1 Answers

Sympy’s lambdify exists exactly for this. Just replace your definition of func with:

func = sp.lambdify((x,A,B),f)
Related