Convert sympy symbolic variable to numpy array

非 Y 不嫁゛ 提交于 2019-12-25 00:18:36

问题


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.)


回答1:


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,



来源:https://stackoverflow.com/questions/56831720/convert-sympy-symbolic-variable-to-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!