Friday, August 21, 2009

Euler Method in Haskell

I decide today to learn haskell, but i can't get out of my head how could it be used in simulation, so, i will try with several basic solvers, starting with Euler Method to solve: y'(t) = f(t, y(t))


--Euler method (t_o, t_f,h, x_o, function(t,x))
euler1 :: Double -> Double -> Double -> Double -> (Double -> Double -> Double) -> [(Double, Double)]
euler1 t_o t_f h x_o f = case t_o < t_f of
True ->
[(t_o,x_o)] ++ (euler1 (t_o+h) t_f h (x_o+(h * f t_o x_o)) f)
False ->
[]



--Euler method (t_o, t_f,steps, x_o, function(t,x))
euler2 :: Double -> Double -> Integer -> Double -> (Double -> Double -> Double) -> [(Double, Double)]
euler2 t_o t_f steps x_o f = case steps > 0 of
True ->
do
let h = (t_f - t_o) / (fromIntegral steps)
[(t_o, x_o)] ++ euler2 (t_o + h) t_f (steps - 1) (x_o + (h * f t_o x_o)) 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(euler1 0 1 0.00001 10 f))
main = putStrLn(show_col(euler2 0 1 100000 10 f))

No comments: