Reputation: 2442
I would like to implement a generic Runge-Kutta step function in Julia language. In Python I can just pass a function as one of the arguments that this RK4 function gets as input. Is there a performance penalty if I do it like that in Julia?
My function looks like this:
function uv_rk4_step(rhs,Vs,Ps)
Vs_k1 = rhs(Vs,Ps)
Vs_k1 = Ps.dt*Vs_k1
Vs_k2 = rhs((Vs+(1/2)*Vs_k1),Ps)
Vs_k2 = Ps.dt*Vs_k2
Vs_k3 = rhs((Vs+(1/2)*Vs_k2),Ps)
Vs_k3 = Ps.dt*Vs_k3
Vs_k4 = rhs((Vs+(1/2)*Vs_k3),Ps)
Vs_k4 = Ps.dt*Vs_k4
Vs_next = Vs+(1/6)*Vs_k1+(1/3)*Vs_k2+(1/3)*Vs_k3+(1/6)*Vs_k4
end
Where Ps is a Julia type that has the parameters of the model, Vs is the multidimensional array of the variables of the ODE, and rhs is the right hand side (partial time derivatives) of the ODE.
Upvotes: 2
Views: 1115
Reputation: 12051
The standard way to do this is just to pass the function as an argument. Using higher-order functions is fast since Julia 0.5.
There are plenty of standard library functions that accept functions as arguments ("higher-order functions"), so this style is idiomatic in Julia. For example, here's a simple implementation of one method for the map
function:
julia> mymap(f, xs) = [f(x) for x in xs]
mymap (generic function with 1 method)
julia> mymap(sin, [0, π/2, 3π/2])
3-element Array{Float64,1}:
0.0
1.0
-1.0
Upvotes: 8