![](/img/trans.png)
[英]python code to solve the following initial value problem ordinary differential equation using Euler method over the interval (o 10)
[英]Solve equation in python over a given time interval with initial condition given
我要解决在python方程在时间间隔I = [0,10]与初始条件(X_0,y_0)=(1,0)和所述参数值μ∈{-2,-1,0,1, 2} 使用函数
scipy.integrate.odeint
然后我想在 xy 平面中绘制解 (x(t;x_0,y_0), y(t;x_0,y_0))。
最初给定的线性系统是
dx/dt = y, x(0) = x_0
dy/dt = - x - μy, y(0) = y_0
请看我下面的代码:
import numpy as np
from scipy.integrate import odeint
sol = odeint(myode, y0, t , args=(mu,1)) #mu and 1 are the coefficients when set equation to 0
y0 = 0
myode(y, t, mu) = -x-mu*y
def t = np.linspace(0,10, 101) #time interval
dydt = [y[1], -y[0] - mu*y[1]]
return dydt
谁能检查我是否正确定义了可调用函数myode ? 此函数计算 ODE 的右侧。
这行代码还显示了一条语法错误消息
def t = np.linspace(0,10, 101) #time interval
说有无效的语法。 我应该以某种方式使用
for * in **
摆脱错误信息? 如果是,具体如何?
我对 Python 和 ODE 很陌生。 有人可以帮我解决这个问题吗? 非常感谢!
尝试使用 solve_ivp 方法。
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import numpy as np
i = 0
u = [-2,-1,0,1,2]
for x in u:
def rhs2(t,y):
return [y[1], -1*y[0] - u[x]*y[1]]
value = u[i]
res2 = solve_ivp(rhs2, [0,10], [1,0] , t_eval=[0,1,2,3,4,5,6,7,8,9,10], method = 'RK45')
t = np.array(res2.t[1:-1])
x = np.array(res2.y[0][1:-1])
y = np.array(res2.y[1][1:-1])
fig = plt.figure()
plt.plot(t, x, 'b-', label='X(t)')
plt.plot(t, y, 'g-', label='Y(t)')
plt.title("u = {}".format(value))
plt.legend(loc='lower right')
plt.show()
i = i + 1
这是solve_ivp方法文档
这是一个非常相似的问题,有更好的解释。
myode
应该是一个函数定义,因此
def myode(u, t, mu): x,y = u; return [ y, -x-mu*y]
时间数组是一个简单的变量声明/赋值,那里不应该有def
。 由于系统是二维的,初始值也需要有二维
sol = odeint(myode, [x0,y0], t, args=(mu,) )
因此,对脚本的最小修改是
def myode(u, t, mu): x,y = u; return [ y, -x-mu*y]
t = np.linspace(0,10, 101) #time interval
x0,y0 = 1,0 # initial conditions
for mu in [-2,-1,0,1,2]:
sol = odeint(myode, [x0,y0], t, args=(mu,) )
x,y = sol.T
plt.plot(x,y)
a=5; plt.xlim(-a,a); plt.ylim(-a,a)
plt.grid(); plt.show()
给情节
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.