我正在尝试用求解一阶微分方程组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)
我发现很少有这种示例被大多数解决方案使用odeint()
。
这两个参数(t,y)是什么,我如何有效地将它们合并到函数中?任何帮助将不胜感激。
您已经用过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, ...
嗨,皮埃尔,非常感谢您的帮助!我做了相关的更改,但是现在出现错误
NameError: name 't' is not defined
(我之前也遇到了)。调用RK45函数时,应该为t和X分配什么?现在我只是RK45(fun=model(t, X)...
一个占位符。我没发现
RK45(fun=model(t, y),
。通过这样做,你传递函数的值model
的t,y
。您需要提供函数本身:RK45(fun=model, ...