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

时间:2019-03-12 12:32:35

标签: python numpy ode

我想用初始条件(x_0,y_0)=(1,0)和参数值μ∈{的时间间隔 I = [0,10]在python中求解方程。 -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非常陌生。有人可以帮我解决这个问题吗?非常感谢你!

2 个答案:

答案 0 :(得分:0)

尝试使用resolve_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

这是resolve_ivp方法Documentation

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

答案 1 :(得分:0)

@Scheduled(cron = "0 0/5 * * * ?") public void fixedDelaySchedule() { System.out.println( "cron task - " + System.currentTimeMillis() / 1000); } 应该是一个函数定义,因此

myode

时间数组是一个简单的变量声明/赋值,那里不应该有def myode(u, t, mu): x,y = u; return [ y, -x-mu*y] 。由于系统是二维的,因此初始值也需要具有二维的

def

因此,对脚本的最小修改是

sol = odeint(myode, [x0,y0], t, args=(mu,) )

给予情节

plot of solutions as per code

相关问题