簡體   English   中英

python function 使用 numpy.array() 返回

[英]python function return using numpy.array()

我正在為我的常微分方程 class 編寫 python 代碼,我必須使用數值方法(RK4)來編寫 model 牛頓第二運動定律。 我相信我的代碼是正確的,因為我自己手工計算了微分方程並驗證了結果。

我想縮短代碼的長度,將類似的 ODE 函數組合在一起,但我遇到了關於返回類型的錯誤。 以下是我到目前為止的工作:

import numpy as np
import matplotlib.pyplot as plt

t0 = 0.0                # Start time
tf = 10.0               # End time
h = 0.001               # step size
t = np.arange(t0,tf,h)  # Time Points
v0 = 20                 # Initial velocity in m/s
theta = 45              # Launch angle
Uy = v0 * np.sin(theta*np.pi/180) # Initial velocity in y component
Ux = v0 * np.cos(theta*np.pi/180) # Initial velocity in x component


def velocity_y(t,v):
    g  = 9.81               # Acceleration of free fall
    dVy_dt = -g
    
    return dVy_dt

def velocity_x(t,v):
    dVx_dt = 0
    
    return dVx_dt

def velocity_xy(t,v):
    g  = 9.81               # Acceleration of free fall
    dVy_dt = -g
    dVx_dt = 0
    
    return np.array([dVy_dt,dVx_dt])

p1,p2 = velocity_xy(t,v)

def rk4( f, x0, t):        
    n = len( t )
    x = np.zeros(n)
    x[0] = x0
    for i in range( n - 1 ):
        h = t[i+1] - t[i]
        k1 = h * f( x[i], t[i] )
        k2 = h * f( x[i] + 0.5 * k1, t[i] + 0.5 * h )
        k3 = h * f( x[i] + 0.5 * k2, t[i] + 0.5 * h )
        k4 = h * f( x[i] + k3, t[i+1] )
        x[i+1] = x[i] + ( k1 + 2.0 * ( k2 + k3 ) + k4 ) / 6.0

    return x

r = rk4(velocity_y,Uy,t)
r1 = rk4(velocity_x,Ux,t)
plt.plot(t,r1,'gx',linestyle='-',label='Velocity in y direction')
plt.xlabel('t or x')
plt.ylabel('v(t) or y(x)')
plt.legend()
plt.grid()
plt.show()

我實現了我的ODE函數如下:

def velocity_y(t,v):
    g  = 9.81               # Acceleration of free fall
    dVy_dt = -g
    
    return dVy_dt

def velocity_x(t,v):
    dVx_dt = 0
    
    return dVx_dt

def velocity_xy(t,v):
    g  = 9.81               # Acceleration of free fall
    dVy_dt = -g
    dVx_dt = 0
    
    return np.array([dVy_dt,dVx_dt])
p1,p2 = velocity_xy(t,v)

我試圖將類似的 ODE 分組到相同的 function 種類中,以避免僅僅為了定義新的 ODE 而過度創建新函數。

def velocity_xy(t,v):
        g  = 9.81               # Acceleration of free fall
        dVy_dt = -g
        dVx_dt = 0
        
        return np.array([dVy_dt,dVx_dt])

我相信錯誤是:

p1,p2 = velocity_xy(t,v)

但我不知道正確的語法。 程序的錯誤:

    NameError                                 Traceback (most recent call last)
<ipython-input-37-4ce3cb1658cb> in <module>
     30     return np.array([dVy_dt,dVx_dt])
     31 
---> 32 p1,p2 = velocity_xy(t,v)
     33 #-----------------------------------------------------------------------------
     34 

NameError: name 'v' is not defined

我將不勝感激任何有用的答案和評論。

我相信主要問題是您將 v 作為參數傳遞給您的def velocity_xy(t,v) function 但沒有在代碼中的任何地方聲明它的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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