繁体   English   中英

用阶梯函数求解微分方程

[英]solving differential equation with step function

我试图解决这个微分方程作为我的任务的一部分。 我无法理解如何在代码中输入u的条件。 在下面显示的代码中,我随意提供

u = 5. 


2dx(t)dt=−x(t)+u(t)

5dy(t)dt=−y(t)+x(t)

u=2S(t−5)

x(0)=0

y(0)=0

where S(t−5) is a step function that changes from zero to one at t=5. When it is multiplied by two, it changes from zero to two at that same time, t=5 where S(t−5) is a step function that changes from zero to one at t=5. When it is multiplied by two, it changes from zero to two at that same time, t=5

def model(x,t,u):
    dxdt = (-x+u)/2
    return dxdt

def model2(y,x,t):
    dydt = -(y+x)/5
    return dydt

x0 = 0
y0 = 0
u = 5
t = np.linspace(0,40)


x = odeint(model,x0,t,args=(u,))
y = odeint(model2,y0,t,args=(u,))
plt.plot(t,x,'r-')
plt.plot(t,y,'b*')
plt.show()

我不太了解SciPy库,但是对于文档中示例,我会尝试这样的事情:

def model(x, t, K, PT)
    """
    The model consists of the state x in R^2, the time in R and the two
    parameters K and PT regarding the input u as step function, where K
    is the infimum of u and PT is the delay of the step.
    """
    x1, x2 = x   # Split the state into two variables

    u = K if t>=PT else 0    # This is the system input

    # Here comes the differential equation in vectorized form
    dx = [(-x1 + u)/2,
          (-x2 + x1)/5]
    return dx

x0 = [0, 0]
K  = 2
PT = 5
t = np.linspace(0,40)

x = odeint(model, x0, t, args=(K, PT))
plt.plot(t, x[:, 0], 'r-')
plt.plot(t, x[:, 1], 'b*')
plt.show()

这里有几个问题,步进功能只是其中的一小部分。 您可以使用简单的lambda定义步进函数,然后只需从外部范围捕获它,甚至不将其传递给您的函数。 因为有时情况并非如此,我们将明确并通过它。 您的下一个问题是要集成的函数中的参数顺序。 根据文档 (y,t,...)。 即,首先是函数,然后是时间向量,然后是其他args参数。 因此,对于第一部分,我们得到:

u = lambda t : 2 if t>5 else 0

def model(x,t,u):
    dxdt = (-x+u(t))/2
    return dxdt

x0 = 0
y0 = 0
t = np.linspace(0,40)


x = odeint(model,x0,t,args=(u,))

转到下一部分,麻烦的是,你不能将x作为arg提供给y,因为它是特定时间的x(t)值的向量,因此y+x在函数中没有意义写了。 如果传递x函数而不是x值,则可以从数学类中遵循直觉。 这样做需要使用您感兴趣的特定时间值插入x值(scipy可以处理,没问题):

from scipy.interpolate import interp1d
xfunc = interp1d(t.flatten(),x.flatten(),fill_value="extrapolate") 
#flatten cuz the shape is off , extrapolate because odeint will go out of bounds
def model2(y,t,x):
    dydt = -(y+x(t))/5
    return dydt
y = odeint(model2,y0,t,args=(xfunc,))

然后你得到:

在此输入图像描述

@Sven的答案更像是scipy / numpy这样的矢量编程。 但我希望我的回答能提供一条更清晰的路径,从你已经知道的工作解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM