在给定初始条件的情况下,在给定时间间隔内用python求解方程

在给定初始条件的情况下,在给定时间间隔内用python求解方程,python,numpy,ode,Python,Numpy,Ode,我想用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 odein

我想用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()
给出情节