![](/img/trans.png)
[英]Issue with odeint from scipy.integrate when I start the range not at 0
[英]How do I fix a value error when using scipy.integrate odeint function?
我是一名工科学生,我正试图弄清楚如何使用 scipy.integrate 模块中的 odeint 函数(我只在 MATLAB 中使用过 ode45)。 我正在尝试数值求解一个简单的二阶质量、弹簧、缓冲器系统。 下面是我编写的代码(特别是我正在使用 Jupyter Notebook 并运行最新版本的 Python 3):
import numpy as np
from scipy.integrate import odeint
from matplotlib.pyplot as plt
%matplotlib inline
# Numerical solution to mx" + bx' + kx = f(t)
# Define state vector y and its derivative
def translational(x,t,m,b,k,f):
y = [x[0], x[1]] # state vector
ydot = [x[1], f -b/m*x[1] - k/m*x[0]] # derivative of state vector
return ydot
# Parameters for the system
t = np.arange(0,10,0.01)
IC = [0, 0] #[x0 v0]
m = 10 # kg
b = 2 # N*s/m
k = 5 # N/m
f = 5*np.cos(10*t)
y = odeint(translational,IC,t,args=(m,b,k,f))
当我执行代码时,它返回以下错误:
TypeError Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
<ipython-input-7-423018367c52> in <module>
20 k = 5 # N/m
21 f = 5*np.cos(10*t)
---> 22 y = odeint(translational,IC,t,args=(m,b,k,f))
~\anaconda3\lib\site-packages\scipy\integrate\odepack.py in odeint(func, y0, t, args, Dfun, col_deriv, full_output, ml, mu, rtol, atol, tcrit, h0, hmax, hmin, ixpr, mxstep, mxhnil, mxordn, mxords, printmessg, tfirst)
239 t = copy(t)
240 y0 = copy(y0)
--> 241 output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
242 full_output, rtol, atol, tcrit, h0, hmax, hmin,
243 ixpr, mxstep, mxhnil, mxordn, mxords,
ValueError: setting an array element with a sequence.
对于我的生活,我无法弄清楚出了什么问题。 任何帮助深表感谢! 谢谢。
f
是一个数字数组,因此f -b/m*x[1] - k/m*x[0]
也是一个数字数组,因此您的函数translational
的返回值不正确。
与其尝试预先计算f
的值,您应该做的是在translational
使用函数的表达式:
def translational(x,t,m,b,k):
y = [x[0], x[1]] # state vector
f = 5*np.cos(10*t)
ydot = [x[1], f -b/m*x[1] - k/m*x[0]] # derivative of state vector
return ydot
并从odeint
函数调用的args
参数中删除f
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.