簡體   English   中英

使用 scipy.integrate odeint 函數時如何修復值錯誤?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM