Skip to content

Instantly share code, notes, and snippets.

@ishiy1993
Created October 20, 2015 06:13
Show Gist options
  • Save ishiy1993/fb713385f77abc78ea8e to your computer and use it in GitHub Desktop.
Save ishiy1993/fb713385f77abc78ea8e to your computer and use it in GitHub Desktop.
Haskellで数値積分
import Data.List (foldl')
-- 長方形近似
integral :: Double -> Double -> Double -> (Double -> Double) -> Double
integral a b dx f = foldl' (+) 0 $ map ((dx *) . f) xs
where xs = [a + dx*x| x <- [0..(b-a)/dx]]
-- 台形近似
integral2 :: Double -> Double -> Double -> (Double -> Double) -> Double
integral2 a b dx f = foldl' (+) 0 $ map (\(y1,y2) -> dx * (y1 + y2) / 2) $ zip ys (tail ys)
where ys = map f [a + dx*x| x <- [0..(b-a)/dx]]
main :: IO ()
main = do
print $ integral 0 pi 0.001 sin
print $ integral2 0 pi 0.001 sin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment