Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Calculate Integral of function
--ghc 7.10 -- calculates one block of the rieman function riemanBlock :: Double -> Double -> (Double -> Double) -> Double riemanBlock (intA, intB) f | intA > intB = riemanBlock (intB, intA) f | otherwise = ((f intA) + (f intB)) / 2.0 * (intB-intA) -- iterates over all blocks of the rieman sum and gives a list of block sizes riemanIterator :: [Double] -> (Double -> Double) -> [Double] riemanIterator [a] _ = [] riemanIterator (p:q:ps) f = (riemanBlock (p, q) f) : (riemanIterator (q:ps) f) -- calculates the rieman sum for the given partition riemanSum :: [Double] -> (Double -> Double) -> Double riemanSum partition f = sum (riemanIterator partition f) -- creates a partition of a given interval with n sub-intervals createPartition :: (Double, Double) -> Double -> [Double] createPartition (intA, intB) n | intA > intB = createPartition (intB, intA) n | otherwise = [intA, intA+(intB-intA)/n .. intB] -- this does all the work, calculate riemanSums over more and more finely divided partitions until the difference between this one and the last one is below prec integralIterator :: Double -> Double -> (Double, Double) -> (Double -> Double) -> Double -> Double integralIterator lastInt lastN (intA, intB) f prec | prec > abs (lastInt - currentInt) = currentInt | otherwise = integralIterator currentInt currentN (intA, intB) f prec where currentN = lastN * 2 currentInt = riemanSum (createPartition (intA, intB) currentN) f -- calculates the integral of f over the interval (intA, intB). The precision can be set in the let-clause integral :: (Double, Double) -> (Double -> Double) -> Double integral (intA, intB) f = let prec = 0.0000000001 in integralIterator (riemanSum [intA, intB] f) 1 (intA, intB) f prec -- int sin(x) from 0 to pi should be 2 main = print $ integral (0, 3.14159) sin
run
|
edit
|
history
|
help
0
Token
haskell_exam
Hanoi solver
project euler 10, haskell
folder
ex3
project euler 7, haskell
prettier Tasty
Knight Journey
Monoid and friends