Saturday, August 22, 2009

Runge Kutta in Haskell

Well, Runge-Kutta is a better solver that Euler so:


-- Runge-Kutta method (t_o, t_f,h, x_o, function(t,x))
runge t_o t_f h x_o f = case t_o < t_f of
True ->
do
let k_1 = f t_o x_o
let k_2 = f (t_o + h/2) (x_o + h * k_1 / 2)
let k_3 = f (t_o + h/2) (x_o + h * k_2 / 2)
let k_4 = f (t_o + h) (x_o + h * k_3)
[(t_o,x_o)] ++ ( runge (t_o + h) t_f h (x_o + h * (k_1 + 2*k_2 + 2*k_3 + k_4) / 6) f)
False ->
[]


-- Function
f :: Double -> Double -> Double
f t x = - x

-- Print in column
show_col :: [(Double, Double)] -> String
show_col x = case x of
(a:b) ->
do
let (t, v) = a
(show t) ++ " , " ++ (show v) ++ "\n" ++ (show_col b)
[] ->
""

main = putStrLn(show_col(runge 0 5 0.01 10 f))

No comments: