如何替换Sympy计算中的变量,以便使用Matplotlib和Numpy绘制?

p4rjhz4m  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(71)

我有这样的计算(积分,然后求和)
结果是s,它是关于自变量xt的。
但是,当我尝试用return s将其定义为u(x,t)时,它无法将x变量替换为我定义为x = np.linspace(0, 20, 50)的变量,并将t变量替换为t = np.linspace(0, 10, 50)。我认为它仍然遵循sympy在开始时定义的xt也是如此。
我想画一个3D图/线框图。Z轴是u(x,t)。希望任何人都能在这方面帮助我。
我的MWE:

import numpy as np
import sympy as sm
from sympy import *
#from spb import *
#from mpmath import nsum, inf

x = sm.symbols("x")
t = sm.symbols("t")
n = sm.symbols("n", integer=True)

L = 20
f1 = (2/L)*x*sin(n*np.pi*x/20)
f2 = (2/L)*(20-x)*sin(n*np.pi*x/20)
fint1 = sm.integrate(f1,(x,0,10))
fint2 = sm.integrate(f2,(x,10,20))

D = 0.475
g = (fint1+fint2)*sin(n*np.pi*x/20)*exp(-(n**2)*(np.pi**2)*D*t/400).nsimplify()
print('')

sm.pretty_print(g)

#gn = g.subs({n:1})

s = 0
for c in range(10):
    s += g.subs({n:c})
    print(s)

print('')
print('The function u(x,t) : ')
print('')
sm.pretty_print(s)

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# defining surface and axes
x = np.linspace(0, 20, 50)
t = np.linspace(0, 10, 50)

def u(x, t):
   return s

X, T = np.meshgrid(x, t)
Z = u(X, T)

print('')
print('u(x,t)')

print(Z)

#fig = plt.figure()
# syntax for 3-D plotting
#ax = plt.axes(projection='3d')
# syntax for plotting
#ax.plot_wireframe(X,T,Z, cmap='viridis',edgecolor='green')
#ax.set_title('Wireframe')
#plt.show()
i1icjdpr

i1icjdpr1#

**第一个选项:**使用sm.lambdifys转换为数值函数,以便稍后进行计算。

xx, tt = np.mgrid[0:20:n, 0:10:n]
f = sm.lambdify((x, t), s)

fig = plt.figure()
n=30j
ax = fig.add_subplot(projection="3d")
ax.plot_wireframe(xx, tt, f(xx, tt))
ax.set_xlabel("x")
ax.set_ylabel("t")

**第二种选择:**使用SymPy Plotting Backend。有了它,你可以避免使用sm.lambdify和Numpy。一切都由模块处理。

plot3d(
    s, (x, 0, 20), (t, 0, 10), {"alpha": 0}, # hide the surface
    wireframe=True, wf_n1=20, wf_n2=10,
    wf_rendering_kw={"color": "tab:blue"} # optional step to customize the wireframe lines
)

此模块的优点是您可以使用不同的打印库。例如,Plotly在3D可视化方面更好:

plot3d(
    s, (x, 0, 20), (t, 0, 10),
    wireframe=True, wf_n1=20, wf_n2=10,
    backend=PB
)

相关问题