Last active
December 13, 2015 21:28
-
-
Save PRotondo/4977480 to your computer and use it in GitHub Desktop.
Haskell : Integration on the unit cube
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# OPTIONS -XFlexibleInstances -XMultiParamTypeClasses #-} | |
-- integrate on the unit cube | |
-- first argument indicates approximate error | |
class Integrable a b where | |
int :: b -> (b->a) -> b | |
instance (Ord a, Floating a) => Integrable a a where | |
int e f = within (e / 2) (integrate f 0 1) | |
instance (Ord b, Floating b, Integrable a b) => Integrable (b->a) b where | |
int e f = within e2 $ integrate (\t -> int e2 (f t)) 0 1 | |
where e2 = e/2 | |
-- example : int 0.00001 (\x y z -> cos x + exp (y + exp z) ) | |
integrate f a b = integ f a b (f a) (f b) | |
integ f a b fa fb = ( (fa + 4*fm + fb) * (b-a) / 6) : zipWith (+) (integ f a m fa fm) (integ f m b fm fb) | |
where | |
m = (a+b) / 2 | |
fm = f m | |
within eps (x: ys@(y:xs)) | abs(x-y) <= eps = y | |
| otherwise = within eps ys |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment