Python odeint 与微分方程中的数组 [英] Python odeint with array in differential equation

查看:55
本文介绍了Python odeint 与微分方程中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个一阶微分方程(示例):

I have next first order differential equation (example):

dn/dt=A*n;n(0)=28

当A为常数时,用python odeint完美解决.但是我有一个来自 .txt 文件的不同 A 值的数组[不是函数,只是一个值数组]

When A is constant, it is perfectly solved with python odeint. But i have an array of different values of A from .txt file [not function,just an array of values]

A = [0.1,0.2,0.3,-0.4,0.7,...,0.0028]

而且我希望在求解 ode A 的每次迭代(或在每个时刻 t 中)是数组中的一个新值.我的意思是:第一次迭代(或 t=0) - A=0.1第二次迭代(或 t=1) - A=0.2 等来自数组.

And i want that in each iteration (or in each moment of time t) of solving ode A is a new value from array. I mean that: First iteration (or t=0) - A=0.1 Second iteration (or t=1) - A=0.2 and etc from array.

我如何使用 python odeint 来做到这一点?

How can i do it with using python odeint?

推荐答案

是的,你可以,但不能直接在 odeint 中,因为它没有事件机制,而你的提议需要一个事件-动作机制.

Yes, you can to that, but not directly in odeint, as that has no event mechanism, and what you propose needs an event-action mechanism.

但是你可以把你的问题分成几个步骤,在每个步骤中使用 odeint 和现在不变的 A 参数,然后最后加入这些步骤.

But you can separate your problem into steps, use inside each step odeint with the now constant A parameter, and then in the end join the steps.

T = [[0]]
N = [[n0]]
for k in range(len(A)):
    t = np.linspan(k,k+1,11);
    n = odeint(lambda u,t: A[k]*u, [n0],t)
    n0 = n[-1]
    T.append(t[1:])
    N.append(n[1:])

T = np.concatenate(T)
N = np.concatenate(N)

<小时>

如果您对低效率感到满意,无论是在 ODE 的评估还是在内部步骤的数量上,您也可以将参数实现为分段常数函数.


If you are satisfied with less efficiency, both in the evaluation of the ODE and in the number of internal steps, you can also implement the parameter as a piecewise constant function.

tA = np.arange(len(A));
A_func = interp1d(tA, A, kind="zero", fill_value="extrapolate")
T = np.linspace(0,len(A)+1, 10*len(A)+11);
N = odeint(lambda u,t: A_func(t)*u, [n0], T)

内部步长控制器假设 ODE 函数可以很好地微分到 5 阶或更高阶.然后通过阶跃误差计算中固有的隐式数值微分将跳跃视为高度振荡事件,需要非常小的步长.代码内部有一些缓解措施,通常允许求解器最终跳过这样的跳跃,但与上述第一个变体相比,它需要更多的内部步骤和函数评估.

The internal step size controller works on the assumption that the ODE function is well differentiable to 5th or higher order. The jumps are then seen via the implicit numerical differentiation inherent in the step error calculation as highly oscillatory events, requiring a very small step size. There is some mitigation inside the code that usually allows the solver to eventually step over such a jump, but it will require much more internal steps and thus function evaluations than the first variant above.

这篇关于Python odeint 与微分方程中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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