python - 如何将函数传递给 Python 中的函数?

标签 python function-call runge-kutta

我是 Python 的初级/中级。我编码了一个 4th-order Runge-Kutta method (RK4)进入 Python。它基本上是在求解一个钟摆,但这不是这里的重点。

我想通过以下方式改进 RK4 方法:我希望能够将函数 f 直接传递给 RK4 函数,即 RK4(y_0, n, h) 应该变为 RK4(f,y_0,n, H)。这将有很大的优势,我可以将 RK4 用于描述其他系统的其他 f 函数,而不仅仅是这个单摆。

我试过将简单的函数传递给 RK4,但我做错了。我如何在 Python 中执行此操作?

import numpy as np

def RK4(y_0, n, h):
    #4th order Runge-Kutta solver, takes as input
    #initial value y_0, the number of steps n and stepsize h
    #returns solution vector y and time vector t
    #right now function f is defined below

    t = np.linspace(0,n*h,n,endpoint = False)   #create time vector t
    y = np.zeros((n,len(y_0))) #create solution vector y
    y[0] = y_0 #assign initial value to first position in y
    for i in range(0,n-1):
        #compute Runge-Kutta weights k_1 till k_4
        k_1 = f(t[i],y[i])
        k_2 = f(t[i] + 0.5*h, y[i] + 0.5*h*k_1)
        k_3 = f(t[i] + 0.5*h, y[i] + 0.5*h*k_2)
        k_4 = f(t[i] + 0.5*h, y[i] + h*k_3)
        #compute next y        
        y[i+1] = y[i] + h / 6. * (k_1 + 2.*k_2 + 2.*k_3 + k_4)
    return t,y

def f(t,vec):
    theta=vec[0]
    omega = vec[1]
    omegaDot = -np.sin(theta) - omega + np.cos(t)
    result = np.array([omega,omegaDot])    
    return result

test = np.array([0,0.5])
t,y = RK4(test,10,0.1)

最佳答案

Python 函数也是对象。您可以像传递任何其他对象一样传递它们:

>>> def foo(): print 'Hello world!'
...
>>> foo
<function foo at 0x10c4685f0>
>>> foo()
Hello world!
>>> bar = foo
>>> bar()
Hello world!

只需将一个函数作为额外参数传递给您的 RK4 函数,并将其用作局部变量。

关于python - 如何将函数传递给 Python 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15545383/

相关文章:

python - 使用python打开设备进行原始写入

c - 使用不兼容类型调用的没有原型(prototype)的函数

c++ - 按值传递 2D 数组不起作用

python - Runge-Kutta 四阶方法。向后整合

python - 如何使用 Numpy/Keras 将加载图像的一部分置零?

python - 使用 networkx 寻找弱关系

python - 找出: In how many word a character is present in a given Sentence: PYTHON

c++ - 在 c/c++ 中通过函数在内存中的地址调用函数

python - 尝试通过 Euler 和 Runge_Kutta 方法求解二阶 DE

c - 使用 gsl 编写 Runge-Kutta ODE 求解器