在给定初始条件的给定时间间隔内在python中求解方程

问题描述 投票:-1回答:2

我希望在时间间隔I = [0,10]的时间内用python求解方程式,初始条件(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的新手。任何人都可以帮我解决这个问题吗?非常感谢你!

python numpy ode
2个回答
0
投票

因此,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()

给出情节

plot of solutions as per code


0
投票

尝试使用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方法Documentation

Here是一个非常类似的问题,有更好的解释。

© www.soinside.com 2019 - 2024. All rights reserved.