首页 文章

用阶梯函数求解微分方程

提问于
浏览
3

我试图解决这个微分方程作为我的任务的一部分 . 我无法理解如何在代码中输入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 .

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()

2 回答

  • 3

    我不太了解SciPy图书馆,但关于example in the documentation我会尝试这样的事情:

    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()
    
  • 1

    这里有几个问题,步进功能只是其中的一小部分 . 您可以使用简单的 lambda 定义步骤函数,然后只需从外部范围捕获它,甚至不将其传递给您的函数 . 因为有时会赢得't be the case, we' ll明确并传递它 . 您的下一个问题是要集成的函数中的参数顺序 . 根据docs(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,))
    

    然后你得到:

    enter image description here

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

相关问题