我一直在使用交互式matplotlib小部件来可视化微分方程的解。我已经让它与scipy中的odeint函数一起工作,但是没有设法让它与ode类一起更新。我宁愿使用后者,因为它可以更好地控制使用哪个解算器。你知道吗
下面的代码用于求解指数衰减的微分。y0是衰减的振幅。当求解器.集成(t1)在update函数内部调用。我不知道这是为什么。你知道吗
from scipy.integrate import ode
# solve the system dy/dt = f(t, y)
def f(t, y):
return -y / 10
# Array to save results to
def solout(t, y):
sol.append([t, *y])
solver = ode(f).set_integrator('dopri5')
solver.set_solout(solout)
# Initial conditions
y0 = [1] # Initial amplitude
t0 = 0 # Start time
t1 = 20 # End time
fig = plt.figure(figsize=(10, 6))
fig.subplots_adjust(left=0.25, bottom=0.4)
ax = plt.subplot(111)
# solve the DEs
solver.set_initial_value(y0, t0)
sol = []
solver.integrate(t1)
sol = np.array(sol)
t = sol[:, 0]
y = sol[:, 1]
l, = plt.plot(t, y, lw=2, color='red')
plt.axis([0, 20, 0, 1.1])
plt.xlabel('Time (ms)')
plt.ylabel('n1(t)')
plt.grid()
axcolor = 'lightgoldenrodyellow'
axn1 = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
sn1 = Slider(axn1, 'y(0)', 0, 1.0, valinit=1)
def update(val):
y0 = [sn1.val]
solver.set_initial_value(y0, t0)
sol = []
solver.integrate(t1)
sol = np.array(sol)
t = sol[:, 0]
y = sol[:, 1]
l.set_data(t, y)
plt.draw()
sn1.on_changed(update)
我想把计算和绘图分开总是明智的。因此,首先尝试用一些给定的初始条件来求解常微分方程。一旦成功了,试着设计和互动的东西。你知道吗
在您的例子中,我们将构建一个函数来求解ODE,然后在绘图更新中使用具有不同初始条件的函数。你知道吗
相关问题 更多 >
编程相关推荐