问题描述
我是Python的初学者/中级.我已将四阶Runge-Kutta方法(RK4)编码为Python.它基本上是在解决钟摆问题,但这不是重点.
I am a beginner/intermediate in Python. I have coded a 4th-order Runge-Kutta method (RK4) into Python. It is basically solving a pendulum, but that is not the point here.
我想通过以下方式改进RK4方法:我希望能够将函数f直接传递给RK4函数,即RK4(y_0,n,h)应该变成RK4(f,y_0,n, H).这将具有很大的优势,那就是我可以将RK4用于描述其他系统的其他f函数,而不仅仅是这个钟摆.
I want to improve the RK4 method in the following way: I want to be able to pass the function f directly to the RK4 function, i.e. RK4(y_0, n, h) should become RK4(f,y_0,n,h). This would have the great advantage that I could use RK4 for other f functions that describe other systems, not just this one pendulum.
我一直在尝试将简单的函数传递给RK4,但是我做错了.如何在Python中执行此操作?
I have played around with just passing simple functions to RK4, but I am doing something wrong. How do I do this in 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函数也是对象.您可以像其他任何对象一样传递它们:
Python functions are objects too. You can pass them around like any other object:
>>> def foo(): print 'Hello world!'
...
>>> foo
<function foo at 0x10c4685f0>
>>> foo()
Hello world!
>>> bar = foo
>>> bar()
Hello world!
只需将函数作为附加参数传递给您的RK4
函数,并将其用作局部变量即可.
Simply pass a function as an extra parameter to your RK4
function and use that as a local variable.
这篇关于如何在Python中将函数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!