Skip to main content
 首页 » 编程设计

python之在 python 中通过函数传递变量的问题

2025年05月04日10Leo_wl

我很难理解下面代码中的函数 rhs(u, m, r) 是如何接收参数 m 和 r。从代码中可以看出,函数rhs在函数euler_step(u, rhs, dt)中被调用,但是参数m 和 r 作为参数传递给函数 euler_step,它们也不是全局变量。所以,有人可以向我解释参数 m 和 u 是如何到达函数 rhs 的。

# model parameters: 
mpo = 100.   # initial mass of the rocket propellant in kg 
ms = 50.     # mass of the rocket shell in kg 
g = 9.81     # gravity in m s^{-2} 
rho = 1.091  # average air density in kg/m^{3} 
rad = 0.5    # radius of the maximum cross sectional area of the rocket in m 
A = numpy.pi*(rad**2)# maximum cross sectional area of the rocket in m^{2} 
v_e = 325.   # the exhaust speed in m/s 
C_D = 0.15   # drag coefficient 
rt = 20.0    # propellant burn rate in kg/s 
dtp = 5.0    # time interval to empty the propellant in s 
 
### set initial conditions ### 
h0 = 0.0 # start at the zero height [m] 
v0 = 0.0 # initial speed [m/s] 
 
def rhs(u, m, r): 
    """Returns the right-hand side of the phugoid system of equations. 
 
    Parameters 
    ---------- 
    u : array of float 
        array containing the solution at time n. 
    mp: float 
        mass of the propellant at time t 
    mp_rate: float 
        propellant burn rate 
 
    Returns 
    ------- 
    dudt : array of float 
        array containing the RHS given u. 
    """ 
    print("[m,r]",[m,r]) 
    [h,v] = u.copy() 
 
    return numpy.array( [ v, -g + pow((ms+m),-1)*(r*v_e - 0.5*rho*v*abs(v)*A*C_D) ] ) 
 
def euler_step(u, rhs, dt): 
    """Returns the solution at the next time-step using Euler's method. 
 
    Parameters 
    ---------- 
    u : array of float 
        solution at the previous time-step. 
    rhs : function 
        function to compute the right hand-side of the system of equation. 
    dt : float 
        time-increment. 
 
    Returns 
    ------- 
    u_n_plus_1 : array of float 
        approximate solution at the next time step. 
    """ 
 
    return u + dt * rhs(u, m, r) 
 
if __name__ == "__main__": 
    T = 17.0                     # final time 
    dt = 0.1                     # time increment 
    t = numpy.arange(0.0, T, dt) # time discretization 
    N = len(t)                   # number of time-steps 
 
    # initialize the array containing the solution for each time-step 
    u = numpy.zeros((N, 2)) 
    u[0] = numpy.array([h0, v0]) # fill 1st element with initial values 
    rate = numpy.zeros(N) 
    mp = numpy.zeros(N) 
    Np = int(((N)/(T))*dtp) # number of time-steps with propellant burn 
 
    rate[0:Np] = rt # propellant burn rate in kg/s 
    mp[0:Np] = mpo - rt*t[0:Np] 
 
    # time loop - Euler method 
    for n in range(1,N-1): 
 
        r = rate[n] 
        m = mp[n] 
        print("[R,M]",[r,m]) 
        u[n+1] = euler_step(u[n], rhs, dt) 

提前致谢。

请您参考如下方法:

m 和 n 是全局变量。

这可能会造成混淆,因为它可能看起来 __main__ 是一个函数,但实际上不是。 if __name__ == "__main__".... 在全局范围内运行。