将sympy符号变量转换为numpy数组 [英] Convert sympy symbolic variable to numpy array

查看:578
本文介绍了将sympy符号变量转换为numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一个包含一个sympy符号变量的卷积,然后将其转换为一个numpy数组.

I want to perform a convolution that contains a sympy symbolic variable, then convert it to a numpy array.

我的MWE是:

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

我尝试使用建议的解决方案此处,但出现错误TypeError: can't convert expression to float.我不确定如何解决此问题.

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.

(注意:这是MWE.我实际使用的实际fg比这篇文章中定义的洛伦兹主义者要复杂得多.)

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

推荐答案

在尝试绘制符号项时,出现的错误是sympy行,

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

如果您将转换后的my_fog用于xlist

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,

这篇关于将sympy符号变量转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆