Reputation: 3973
I want to perform a convolution that contains a sympy symbolic variable, then convert it to a numpy array.
My MWE is:
from numpy import pi, float64, linspace
from scipy.signal import fftconvolve
import matplotlib.pyplot as plt
from sympy import symbols
from sympy.utilities.lambdify import lambdify
a = 0.657
b = 0.745
c = 0.642
d = 0.343
x = symbols('x')
f = 2*b / ((x-a)**2 + b**2)
g = 2*d / ((x-c)**2 + d**2)
fog = fftconvolve(f,g,mode='same')
fog_fun = lambdify(x,fog,'numpy') # returns a numpy-ready function
xlist = linspace(-20,20,int(1e3))
my_fog = fog_fun(xlist)
dx = xlist[1]-xlist[0]
fog1 = 4*pi*(b+d)/((x-a-c)**2+(b+d)**2) # correct analytic solution
plt.figure()
plt.plot(x,fog1,lw=2,label='analytic')
plt.plot(x,my_fog*dx,lw=2,label='sympy')
plt.grid()
plt.legend(loc='best')
plt.show()
I have tried to use the solution suggested here, but I get the error TypeError: can't convert expression to float
. I'm not sure how to fix this.
(Note: this is a MWE. The actual f
and g
I'm actually using are much more complicated than the Lorentzians defined in this post.)
Upvotes: 0
Views: 1192
Reputation: 13216
The error you have is with the sympy line, as you're trying to plot the symbolic terms,
plt.plot(x,fog1,lw=2,label='analytic')
if you use the converted my_fog
against xlist
plt.plot(xlist,my_fog*dx,lw=2,label='sympy')
it looks like a Lorentzian distribution,
Upvotes: 1