[英]how to solve a system of differential ecuations and a linear equation in Python
I tried to solve this equation system that are two ordinary differential equations and a linear equation我试图求解这个方程组,它是两个常微分方程和一个线性方程
dx(t)/dt = (-x(t) + u(t)) / 2.0,
dy(t)/dt = (-y(t) + x(t)) / 5.0
u(t) = x(t) + 3*y(t)
With this initial conditions x(0) = 0
, y(0) = 0
and u(0)=1
.有了这个初始条件
x(0) = 0
, y(0) = 0
和u(0)=1
。 I have been trying to solve the system using odeint but I don't know hoy to define the linear function, this is, the function u.我一直在尝试使用 odeint 解决系统问题,但我不知道如何定义线性 function,即 function u。 I don't know if it is another way to solve this system.
我不知道这是不是解决这个系统的另一种方法。
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def f(z,t,u):
dzdt = np.zeros(2,)
x = z[0]
y = z[1]
dzdt[0] = (-x + u) / 2.0
dzdt[1] = (-y + x) / 5.0
return dzdt
z0 = [0,0]
n = 150
t = np.linspace(0,15, n)
u = np.zeros(n)
u[0] = 1
x = np.zeros(n)
y = np.zeros(n)
for i in range (1,n):
tspan = [t[i-1],t[i]]
z = odeint(f,z0,t,args=(u[i],))
u[i] = x[i] + 3*y[i]
z0 = z[1]
x[i] = z0[0]
y[i] = z0[1]
plt.plot(t,u)
plt.plot(t,x)
plt.plot(t,y)
plt.show()
You can just substitute u into the other equations.您可以将 u 代入其他方程式。 Also these particular ODEs can be solved symbolically using SymPy:
这些特定的 ODE 也可以使用 SymPy 以符号方式求解:
In [34]: x, y, u = symbols('x, y, u', cls=Function)
In [35]: t = symbols('t')
In [36]: eqs = [Eq(x(t).diff(t), (-x(t) + u(t)) / 2.0),
...: Eq(y(t).diff(t), (-y(t) + x(t)) / 5.0),
...: Eq(u(t), x(t) + 3*y(t))]
In [37]: eqs[2]
Out[37]: u(t) = x(t) + 3⋅y(t)
In [38]: eqs_new = [eq.subs(eqs[2].lhs, eqs[2].rhs) for eq in eqs[:2]]
In [39]: eqs_new
Out[39]:
⎡d d ⎤
⎢──(x(t)) = 1.5⋅y(t), ──(y(t)) = 0.2⋅x(t) - 0.2⋅y(t)⎥
⎣dt dt ⎦
In [41]: dsolve(eqs_new)[0]
Out[41]:
-0.656776436283002⋅t 0.456776436283002⋅t
x(t) = - 2.28388218141501⋅C₁⋅ℯ + 3.28388218141501⋅C₂⋅ℯ
In [42]: dsolve(eqs_new)[1]
Out[42]:
-0.656776436283002⋅t 0.456776436283002⋅t
y(t) = 1.0⋅C₁⋅ℯ + 1.0⋅C₂⋅ℯ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.