求解ODE系统时,对scipy.integrate.ode使用自适应时间步长 [英] Using adaptive time step for scipy.integrate.ode when solving ODE systems

查看:180
本文介绍了求解ODE系统时,对scipy.integrate.ode使用自适应时间步长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须阅读在scipy.integrate中使用自适应步长.ode 和该问题的公认解决方案,甚至在我的Python解释器中通过复制和粘贴来复制结果.

I have to just read Using adaptive step sizes with scipy.integrate.ode and the accepted solution to that problem, and have even reproduced the results by copy-and-paste in my Python interpreter.

我的问题是,当我尝试使解决方案代码适应我自己的代码时,我只会得到平线.

My problem is that when I try and adapt the solution code to my own code I only get flat lines.

我的代码如下:

from scipy.integrate import ode
from matplotlib.pyplot import plot, show

initials = [1,1,1,1,1]
integration_range = (0, 100)

f = lambda t,y: [1.0*y[0]*y[1], -1.0*y[0]*y[1], 1.0*y[2]*y[3] - 1.0*y[2], -1.0*y[2]*y[3], 1.0*y[2], ]

y_solutions = []
t_solutions = []
def solution_getter(t,y): 
   t_solutions.append(t)
   y_solutions.append(y) 


backend = "dopri5"
ode_solver = ode(f).set_integrator(backend)
ode_solver.set_solout(solution_getter)
ode_solver.set_initial_value(y=initials, t=0)

ode_solver.integrate(integration_range[1])

plot(t_solutions,y_solutions)
show()

它产生的图:

推荐答案

在此行

   y_solutions.append(y) 

您认为您要附加当前向量.实际上发生的是您将对象引用附加到y.显然,由于积分器在积分循环期间重用了向量y,因此您始终会附加相同的对象引用.因此,最后,列表的每个位置由指向y最后状态的向量的相同引用填充.

you think that you are appending the current vector. What actally happens is that you are appending the object reference to y. Since apparently the integrator reuses the vector y during the integration loop, you are always appending the same object reference. Thus at the end, each position of the list is filled by the same reference pointing to the vector of the last state of y.

长话短说:替换为

    y_solutions.append(y.copy()) 

一切都很好.

这篇关于求解ODE系统时,对scipy.integrate.ode使用自适应时间步长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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