Skip to content

Instantly share code, notes, and snippets.

@ishiy1993
Created October 23, 2015 00:32
Show Gist options
  • Save ishiy1993/c92aa2c0c490d4cdca3e to your computer and use it in GitHub Desktop.
Save ishiy1993/c92aa2c0c490d4cdca3e to your computer and use it in GitHub Desktop.
Haskellで2次ルンゲ・クッタ法(改良オイラー法)
import Data.List (unfoldr)
-- dy/dx = f
f x y = - a * y
-- パラメータ
a = 1
-- 区間と初期値
x0 = 0
x1 = 5
y0 = 1
-- 分割数
n = 100
dx :: Double
dx = (x1 - x0) / n
rk2 :: (Double,Double) -> Maybe ((Double,Double),(Double,Double))
rk2 xy@(x,y) | x < x1 = Just (xy,xy')
| otherwise = Nothing
where xy' = (x', y')
x' = x + dx
y' = y + dx * (f (x+dx/2) y'')
y'' = y + dx/2 * (f x y)
main :: IO ()
main = writeFile "rk2.dat" . toData $ unfoldr rk2 (x0,y0)
toData :: [(Double,Double)] -> String
toData xys = unlines $ map (\(x,y) -> (show x) ++ " " ++ (show y)) xys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment