温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Issue understanding scipy.integrate.RK45 requirements
differential-equations python runge-kutta scipy

python - 问题理解scipy.integrate.RK45要求

发布于 2021-01-17 13:49:41

我正在尝试用求解一阶微分方程组scipy.integrate.RK45()我已经编写了我希望绘制的模型函数的脚本(位移与时间),但是RK45()要求该函数接受2个参数,即“ t”和“ y”,其中“ t”是标量,“ y”是就我而言。下面对此进行了更好的描述:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.RK45.html

我的脚本如下:

import numpy as np
from scipy.integrate import RK45, RK23

# Model the calling function [X_dot]:
#------------------------------------------------------------------
def model(t, y):
    
    # Define the mass, stiffness and damping [m, c, k]:
    m = 2
    c = 10
    k = 1500

    # Define the piecewise forcing function [F]:
    if (t >= 0 and t < 0.1):
        F = 200 * t
    if (t >= 0.1 and t < 0.25):
        F = 20
    else:
        F = 0
    
    E_matrix = [[0, 1], [(-k / m), (-c / m)]]
    Q_matrix = [0, F / m]

    return E_matrix*X + Q_matrix

# Define the initial conditions and integration boundaries:
#------------------------------------------------------------------
time_step = 0.01
t_upper = 0.5
t_lower = 0

initial_conditions = [0, 0] # [displacement(t=0) = 0, velocity(t=0) = 0]

points_to_plot = RK45(fun=model(t, y), t0=t_lower, y0=initial_conditions, t_bound=t_upper, vectorized=True)

我想解决的系统图如下所示: DE系统

我发现很少有这种示例被大多数解决方案使用odeint()

这两个参数(t,y)是什么,我如何有效地将它们合并到函数中?任何帮助将不胜感激。

查看更多

提问者
ChaddRobertson
被浏览
55
Pierre de Buyl 2020-09-18 20:49

您已经用过t现在,更改def model(t, y):def model(t, X):,您也将使用X请注意,t和y是位置参数,可以根据需要在函数中调用它们。您还有另一个问题,那就是您要乘以Python列表!与Matlab相对,在Python中,您需要指定要创建一个数组:

更改

E_matrix = [[0, 1], [(-k / m), (-c / m)]]
Q_matrix = [0, F / m]

E_matrix = np.array([[0, 1], [(-k / m), (-c / m)]])
Q_matrix = np.array([0, F / m])

return E_matrix*X + Q_matrix

return E_matrix @ X + Q_matrix

就像@NumPy中的矩阵乘积一样。*执行按元素积。

编辑:我没有发现电话RK45(fun=model(t, y),这样,您可以在传递函数模型的值t,y您需要提供函数本身:RK45(fun=model, ...